websocket使用

websocket是HTML5 开始提供的一种在单个 TCP 连接上进行全双工通讯的协议。

在开发中需要做到数据库的数据实时更新到页面中,那么就可以使用websocket来实现。

首先需要初始化:

initWebsocket () {
  this.websocket = new WebSocket('ws://xxxxxx') // 此处需要后台地址
  this.websocket.onopen = this.websocketOpen // 连接建立时触发
  this.websocket.onmessage = this.websocketMessage // 客户端接收服务端数据时触发
  this.websocket.onerror = this.websocketError // 通信发生错误时触发
  this.websocket.onclose = this.websocketClose // 连接关闭时触发
}

打开连接:

websocketOpen () {
  console.log('websocket连接创建成功')
  // 通知服务端发送message
  this.$api.commonPost('xxx')
}

接收信息:

websocketMessage ({ data }) {
  console.log('接收到的message', data)
  data = JSON.parse(data)
}

通信错误:

websocketError (error) {
  console.log('通信出现错误', error)
} 

通信结束:

websocketClose () {
  console.log('通信已关闭')
} 

 

posted @ 2023-03-13 16:07  圆圆呀~  阅读(79)  评论(0编辑  收藏  举报