关于websocket发送数据格式问题

2,509 阅读1分钟

众所周知,大家在开发websocket的时候都会使用类似于“心跳”的方式来检查前后台是否断开连接了,在打开websocket的时候,有一个onopen的回调,在里面前端开启一个定时器,每隔几十秒给后台发送一个ping消息,后台收到后会回复一个pong消息,消息的结构体要一致,这一来一回ping-pong完成一次心跳,说明长链接没有断开。由于我们的后台用的是golang,说要发byte的数据类型,心想,我们js前端哪里有这个类型啊,于是直接用JSON.stringfy转一下发送过去,发现不行。然后在网上查了一遍,说可以用TextEncoder()来编码发送过去,然后后台发回来的数据用TextDecoder()来解码!以下为核心代码

_websocketonopen(e) {
      console.log("WebSocket连接成功");
      this.timer = setInterval(() => {
        let msg = {
          ops: 25,
        }
        var decc = new TextEncoder()
        this.websock.send(decc.encode((JSON.stringify(msg)))); //给服务器发送ping
        this.pingNumer++;
        console.log("this.pingNumer", this.pingNumer)
        if (this.pingNumer > 5) { //发送三次无响应后重连
          console.log("coming close websocket")
          this.reconnectWebsocket()
          clearTimeout(this.timer)
        }
      }, 50000);
    },
    _websocketonmessage(e) {
      //数据接收
      var decc = new TextDecoder("utf-8");
      let result = JSON.parse(decc.decode(e.data));
      console.log('websocket接受消息-------------------------', result)
      }