WebSocket示例解析(可直接使用)

示例代码

前言,本代码用JS语言书写,自己使用环境是cocoscreatorv2.4.2版本,适用于小游戏长链接通信(未使用probuffer),可直接拿用。代码中用到的log.debu日志打印函数,是我自己的一层日志打印封装。


let WebSocketUitils = {

    socket: WebSocket,//声明变量类型
    helper: null,//事件分发中转对象
    isInit: false,//是否初始化完成
    lockReconnect: false,//是否正在重连

    //初始化websocket
    initWebSocket(){
        let host = '';//ws地址
        // log.debug('websocket----connect:', host);
        this.socket = new WebSocket(host);

        this.socket.onopen = (event)=>{
            log.debug('websocket----------onopen---------->', event);
            this.isInit = true;
            this.lockReconnect = false;
            this.tryReconnect = null;
            this.timeoutNum = 3;
            this.heartCheck();
        };

        this.socket.onmessage = (event)=>{
            let data = event.data;
            data = JSON.parse(data);
            // log.debug('websocket----------onmessage---------->', data);
            if(data.type == "heartBeat"){
                //重置心跳超时次数
                this.timeoutNum = 3;
                //发送心跳
                this.heartCheck();
            }else{
                //事件分发
                this.helper.onmessage(data);
            }
        };

        this.socket.onerror = (event)=>{
            log.debug('websocket----------onerror---------->', event);
            //重连(此处可不进行重连,因onerror调用后、会onclose方法会被调用触发重连)
            //this.socket = null;
            //this.reconnect();
        };

        this.socket.onclose = (event)=>{
            log.debug('websocket----------onclose---------->', event);
            //重连
            this.socket = null;
            this.reconnect();
        };
    },

    send(data){
        log.debug('发送消息~~~~~~~~~~~~', data);
        if (!this.isInit){
            log.debug('WebSocket is not inited...');
        }else if(this.socket.readyState == WebSocket.OPEN){
            log.debug('WebSocket send:', data);
            this.socket.send(data);
        }else{
            log.debug('WebSocket readState:', this.socket.readyState);
        }
    },

    close(){
        if (this.socket){
            log.debug("WebSocket close...");
            this.socket.close();
            this.socket = null;
        }
    },

    //重连
    tryReconnect: null,
    reconnect() {
        //判断是否正在重连
        if(this.lockReconnect) {
            return;
        };
        this.lockReconnect = true;
        //没连接上会一直重连,设置延迟避免请求过多
        this.tryReconnect && clearTimeout(this.tryReconnect);
        this.tryReconnect = setTimeout(()=>{
            this.initWebSocket();
        }, 4000);
    },

    /*~~~~~~~~~~~~~~~~~~~~~~~~~~心跳~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
    timeoutNum: 3,//超过三次进行重连
    heartTime: 3000, //每隔三秒发送心跳
    heartObj: null,
    heartCheck(){
        this.heartObj && clearTimeout(this.heartObj);
        this.heartObj = setTimeout(()=>{
            //发送一个心跳,后端收到后,返回一个心跳消息,拿到返回的心跳就说明连接正常
            let msg = {"msg": "ping"};
            this.socket && this.socket.send(JSON.stringify(msg));// 心跳包
            //3次心跳均未响应重连
            this.timeoutNum--;
            //计算答复的超时次数
            if(this.timeoutNum === 0) {
                this.close();
                this.reconnect();
            }else{
                this.heartCheck();
            }
            // log.debug('心跳~~~~~~~~~~~~~~~~~~~~~~', this.heartObj);
        }, this.heartTime);
    },
}

module.exports = WebSocketUitils;

至此,结束。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值