前端开发实时通信之:webSocket 实战篇

webSocket 实战篇

[toc]

  1. 常见场景
  2. 实时数据监听

场景一: 实时通信 get数据模式

  1. 场景介绍:与服务端建立长连接,频繁实时获取服务端发来的数据,即时通信
  2. 需求分析:数据实时更新,保证服务端有新数据,客户端即刻响应并更新数据
  3. 技术目标:保证与服务端的通信时刻连通
  4. 技术思路:通过对websocket state的监听,根据不同的状态分类处理, 关闭、错误 => 重连, 获得到消息 => 开启心跳监测

示例

    const ws = new WebSocket('ws://ezlost')
    //websocket 关闭、错误时尝试重连
    ws.onclose = () => reConnect()
    ws.onerror = () => reConnect()
    //心跳监测
    ws.onmessage = () => {
        //根据你的需求确定监听时长
        beatPack(ws, 5000).beat()
        ...
    }

    //重连
    function reConnect(){
        const _this = this
        const connect = {
            timer: null,
            wait: 5000, //自定义,控制重连频率
            reconnect: function(){
                if(this.timer) return;
                this.timer = setTimeout(() => {
                    _this.ws = new WebSocket('ws://ezlost')
                    clearTimeout(this.timer)
                    this.timer = null
                }, this.wait);
            }
        }
        connect.reconnect() 
    }

    //心跳监听
    function beatPack(socketObj = {}, wait = 1000){     
        return {
            beatTimer: null,
            closedTimer: null,
            beat: function(){
                clearTimeout(this.beatTimer)
                clearTimeout(this.closedTimer)
                this.beatTimer = null
                this.beatTimer = setTimeout(() => {
                    socketObj.readyState === 1 && socketObj.send('HEARTBEAT')
                    this.closedTimer = setTimeout(() => {
                        socketObj.close() //超时关闭websocket
                    }, wait);
                }, wait);
            }
        }
    }

实时通信 post模式

  1. 场景介绍:与服务端建立连接,实时向服务端发送消息
  2. 需求分析:数据实时、频繁发送,保证客户端发送消息时与服务端的连通
  3. 技术目标:保证与服务端的通信需要时保持连通
  4. 技术思路:通过对websocket state的监听,根据不同的状态分类处理, 关闭、错误 => 重连, 消息状态判断 => 发送数据

示例

    const ws = new WebSocket('ws://ezlost')
    ws.onclose = () => reConnect(data)
    ws.onerror = () => reConnect(data)
    //websocket 关闭、错误时尝试重连

    const postwsActions = {
        '0': () => { ws.onopen = () => ws.send(data) },
        '1': () => ws.send(data),
    }
    postwsActions[ws.readyState] && postwsActions[ws.readyState]()

    //重连
    function reConnect(data){
        const _this = this
        const connect = {
            timer: null,
            wait: 5000, //自定义,控制重连频率
            reconnect: function(){
                if(this.timer) return;
                this.timer = setTimeout(() => {
                    _this.ws = new WebSocket('ws://ezlost')
                    _this.ws.onopen = () => ws.send(data)
                    clearTimeout(this.timer)
                    this.timer = null
                }, this.wait);
            }
        }
        connect.reconnect() 
    }

上一篇
下一篇