【js小技巧】websocket使用

196 阅读1分钟

背景

很多双向数据都应用websocket。

理论

参考developer.mozilla.org/zh-CN/docs/…

可以把 WebSocket 看成是 HTTP 协议为了支持长连接所打的一个大补丁,它和 HTTP 有一些共性,是为了解决 HTTP 本身无法解决的某些问题而做出的一个改良设计。在以前 HTTP 协议中所谓的 keep-alive connection 是指在一次 TCP 连接中完成多个 HTTP 请求,但是对每个请求仍然要单独发 header;所谓的 polling 是指从客户端(一般就是浏览器)不断主动的向服务器发 HTTP 请求查询是否有新数据。这两种模式有一个共同的缺点,就是除了真正的数据部分外,服务器和客户端还要大量交换 HTTP header,信息交换效率很低。它们建立的“长连接”都是伪.长连接,只不过好处是不需要对现有的 HTTP server 和浏览器架构做修改就能实现。

使用


第一阶段:create
initWebSocket() {
  // 初始化weosocket
  const wsuri = WsUrl
  this.websock = new WebSocket(wsuri)
  this.websock.onmessage = this.websocketonmessage
  this.websock.onopen = this.websocketonopen
  this.websock.onerror = this.websocketonerror
  this.websock.onclose = this.websocketclose
},

第二阶段:onopen

websocketonopen() {
  // 连接建立之后执行send方法发送数据
  const actions = {
  }
  for (const key of Object.keys(actions)) {
    if (!actions[key]) {
      delete actions[key]
    }
  }
  console.log(actions)
  this.websocketsend(JSON.stringify(actions))
},
 websocketsend(Data) {
  // 数据发送
  this.websock.send(Data)
},

第三阶段:onmessage

async websocketonmessage(e) {
  // 数据接收
  if (!e.data) {
    // console.log(this.errCount)
    if (this.errCount > 500) {
      this.closeLoading()
      this.websock && this.websock.close()
      this.$message('无数据返回')
    }
    this.errCount = this.errCount + 1
    return
  }
  const originData = e.data === '0' ? e.data : JSON.parse(e.data)
  console.log(originData)
  }
  

第四阶段:结束和异常

  websocketonerror() {
  // 连接建立失败重连
  // console.log('ws创建失败')
},
    async websocketclose(e) {
  // 关闭
  // console.log('断开连接', e)
},

比较简单,不展开描述了。