侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

在js的websocket客户端开发中遇到代码割裂情况解决方案

前端  /  管理员 发布于 1年前   364

什么是代码割裂的情况?用一个例子说明。

在 login 方法发送登录,在 onmessage 方法处理登录的返回结果。

这种情况有两个弊端:

1.处理逻辑割裂,一整个逻辑被分割到两个地方处理。
2.上下文割裂,比如登录失败,我需要在登录按钮的边上搞个提示语,
 因为处理逻辑被割裂到两个函数,导致通过 onclick 传递的 this,被丢失了。

示例代码:

<style>
    div {
        margin: 10px;
    }
</style>
<div>
    <a href="javascript:;" onclick="socket.connect()">打开连接</a>
    <a href="javascript:;" onclick="socket.close()">关闭连接</a>
</div>
<div>
    <label for="j-token">token</label><input type="text" id="j-token" value="WagCUcmxoUB3brbT">
    <a href="javascript:;" onclick="login(this)" id="j-login">登录</a>
</div>
<script>
    const socket = {
        _ws: null,
        _heartbeatIndex: -1,
        _onopen: function () {
            this._heartbeatIndex = setInterval(function () {
                if (!socket._ws) {
                    if (socket._heartbeatIndex > 0) {
                        clearTimeout(socket._heartbeatIndex);
                        socket._heartbeatIndex = -1;
                    }
                    return;
                }
                socket._ws.send('~3yPvmnz~');
            }, 45 * 1000);
        },
        _onmessage: function (event) {
            if (event.data === '~u38NvZ~') {
                return;
            }
            //接收服务端的消息,并进行逻辑处理
            const router = JSON.parse(event.data);
            //处理登录请求的返回
            if (router.cmd === cmd.login) {
                //因为发送登录的逻辑在login函数,所以拿不到触发登录的按钮,只能重新查找。
                let a = document.querySelector('#j-login');
                if (router.code === 0) {
                    a.innerText = '登录成功';
                } else {
                    a.innerText = '登录失败' + router.data;
                }
            }
        },
        _onclose: function () {
            console.log('WebSocket连接已关闭');
        },
        _onerror: function (error) {
            console.log('WebSocket错误: ' + error);
        },
        /**
         * 发送一条消息到服务端
         * @param cmd int
         * @param data object|string
         */
        send: function (cmd, data) {
            if (!this._ws) {
                return;
            }
            if (data instanceof Object) {
                data = JSON.stringify(data);
            }
            let router = {
                cmd: cmd,
                data: data
            };
            this._ws.send(JSON.stringify(router));
        },
        connect: function () {
            this._ws = new WebSocket('ws://127.0.0.1:7272');
            this._ws.onopen = this._onopen;
            this._ws.onmessage = this._onmessage;
            this._ws.onclose = this._onclose;
            this._ws.onerror = this._onerror;
        },
        close: function () {
            if (this._ws) {
                this._ws.close(1000, '主动关闭连接');
                this._ws = null;
            }
        }
    };
    const cmd = {
        login: 3,
    };
    function login(aThis) {
        //这个上下文在websocket对象返回数据时,是拿不到的。
        console.log(aThis);
        let data = {
            token: document.querySelector("#j-token").value,
            type: 2
        };
        socket.send(cmd.login, data);
    }
</script>

解决方案:

用 messageChannel 进行通信。

示例代码:

<style>div {margin: 10px;}</style>
<div>
    <a href="javascript:;" onClick="socket.connect()">打开连接</a>
    <a href="javascript:;" onClick="socket.close()">关闭连接</a>
</div>
<div>
    <label for="j-token">token</label><input type="text" id="j-token" value="WagCUcmxoUB3brbT">
    <a href="javascript:;" onClick="login(this)">登录</a>
</div>
<script>
    const socket = {
        _ws: null,
        _heartbeatIndex: -1,
        _channel: new Map(),
        _onopen: function () {
            this._heartbeatIndex = setInterval(function () {
                if (!socket._ws) {
                    if (socket._heartbeatIndex > 0) {
                        clearTimeout(socket._heartbeatIndex);
                        socket._heartbeatIndex = -1;
                    }
                    return;
                }
                socket._ws.send('~3yPvmnz~');
            }, 45 * 1000);
        },
        _onmessage: function (event) {
            if (event.data === '~u38NvZ~') {
                return;
            }
            //这里有个要求,服务端的返回结构必须是:{cmd: int, code: int, data: mixed}
            //这里有个缺点:如果同一个cmd,被客户端一次性发送两次,那么第一次的请求的响应是被丢弃了,解决这个问题也很简单。
            //我这个只是个demo,就不予解决了。
            const router = JSON.parse(event.data);
            const channel = socket._channel.get(router.cmd);
            socket._channel.delete(router.cmd);
            if (!channel instanceof MessageChannel) {
                console.log('客户端未知的消息:' + event.data);
                return;
            }
            channel.port2.postMessage(router);
        },
        _onclose: function () {
            console.log('WebSocket连接已关闭');
        },
        _onerror: function (error) {
            console.log('WebSocket错误: ' + error);
        },
        /**
         * 发送一条消息到服务端
         * @param cmd int
         * @param data object|string
         * @param timeout int 服务端响应的超时时间,单位秒
         * @returns {Promise<unknown>}
         */
        send: async function (cmd, data, timeout = 60) {
            if (!this._ws) {
                return;
            }
            if (data instanceof Object) {
                data = JSON.stringify(data);
            }
            let router = {
                cmd: cmd,
                data: data
            };
            this._ws.send(JSON.stringify(router));
            const channel = new MessageChannel();
            this._channel.set(cmd, channel);
            return new Promise(function (resolve) {
                let setTimeoutIndex = -1;
                if (timeout > 0) {
                    setTimeoutIndex = setTimeout(function () {
                        socket._channel.delete(cmd);
                        channel.port1.close();
                        channel.port2.close();
                        router.data = '服务端响应超时';
                        router.code = 500;
                        resolve(router);
                    }, 1000 * timeout);
                }
                channel.port1.onmessage = function (event) {
                    if (setTimeoutIndex > 0) {
                        clearTimeout(setTimeoutIndex);
                        setTimeoutIndex = -1;
                    }
                    channel.port1.close();
                    channel.port2.close();
                    resolve(event.data);
                };
                channel.port1.onmessageerror = function (event) {
                    if (setTimeoutIndex > 0) {
                        clearTimeout(setTimeoutIndex);
                        setTimeoutIndex = -1;
                    }
                    socket._channel.delete(cmd);
                    channel.port1.close();
                    channel.port2.close();
                    router.data = '客户端socket接收逻辑错误:' + event.data;
                    router.code = 400;
                    resolve(router);
                };
            });
        },
        connect: function () {
            this._ws = new WebSocket('ws://127.0.0.1:7272');
            this._ws.onopen = this._onopen;
            this._ws.onmessage = this._onmessage;
            this._ws.onclose = this._onclose;
            this._ws.onerror = this._onerror;
        },
        close: function () {
            if (this._ws) {
                this._ws.close(1000, '主动关闭连接');
                this._ws = null;
            }
        }
    };
    const cmd = {
        login: 3,
    };
    async function login(aThis) {
        let data = {
            token: document.querySelector("#j-token").value,
            type: 2
        };
        //发送请求,并接收响应
        let router = await socket.send(cmd.login, data);
        //处理响应
        if (router.code === 0) {
            aThis.innerText = '登录成功';
        } else {
            aThis.innerText = '登录失败' + router.data;
        }
    }
</script>



  • 上一条:
    Laravel框架中适用于Eloquent的日期过滤软件包:lara-date-filter
    下一条:
    在PHP提高性能方式之开启OPCache扩展及OPCache配置参数详解
  • 昵称:

    邮箱:

    3条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 使用 Alpine.js 排序插件对元素进行排序(0个评论)
    • 在js中使用jszip + file-saver实现批量下载OSS文件功能示例(0个评论)
    • 在vue中实现父页面按钮显示子组件中的el-dialog效果(0个评论)
    • 使用mock-server实现模拟接口对接流程步骤(0个评论)
    • vue项目打包程序实现把项目打包成一个exe可执行程序(0个评论)
    • 近期文章
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2017-06
    • 2017-07
    • 2017-08
    • 2017-09
    • 2017-10
    • 2017-11
    • 2018-03
    • 2018-04
    • 2018-05
    • 2018-06
    • 2018-09
    • 2018-11
    • 2018-12
    • 2019-02
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2021-04
    • 2021-05
    • 2021-07
    • 2021-08
    • 2021-09
    • 2021-10
    • 2021-11
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-06
    • 2023-07
    • 2023-09
    • 2023-10
    • 2023-11
    • 2023-12
    • 2024-01
    • 2024-02
    • 2024-03
    • 2024-04
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客