在vue中使用WebScoket

809 阅读1分钟

定义mixins

export default {
  methods: {
    initWebSocket() { //初始化weosocket
      let host = location.host
      let wsuri
      if (location.href.toLowerCase().slice(0, 5) === 'https') {
        wsuri = `wss://${host}/ws/${this.websocket_path}`
      } else {
        wsuri = `ws://${host}/ws/${this.websocket_path}`
      }
      console.log('Connecting to ' + wsuri)
      this.websock = new WebSocket(wsuri)
      this.websock.onmessage = this.on_websocket_message
      this.websock.onopen = this.websocketonopen
      this.websock.onerror = this.websocketonerror
      this.websock.onclose = this.websocketclose
    },
    websocketonopen(){ //连接建立之后执行send方法发送数据
      let actions = {action: "init", data: "init"}
      this.websocketsend(JSON.stringify(actions))
      console.log('Connecting ok.')
    },
    websocketonerror(){//连接建立失败重连
      this.initWebSocket();
    },
    websocketsend(data){//数据发送
      if (typeof(data) !== "string") {
        data = JSON.stringify(data)
      }
      this.websock.send(data)
    },
    websocketclose(e){  //关闭
      console.log('断开连接',e);
    },
  }
}

在页面中使用

  • mixins 混入
mixins: [WebsocketMixin]
  • 设置路径
  data() {
    return {
      websocket_path: 'meetingroom/'
    }
  • 需要初始化WebScoket
  mounted() {
    this.statusMap = statusMap
    this.initWebSocket()
  }
  • 接收数据
    on_websocket_message(response) {
    const form = JSON.parse(response.data)
  }
  ```