vue2 中使用 websocket

871 阅读1分钟

vue2 中使用 websocket

  • websocket 是什么?

    websocket 是一种网络通信协议,类似于 http,用于满足前后端数据通信的,能更好的节省服务器资源并达到实时通信。

  • websocket 和 http 的区别

    websocket :是双向通信协议,可以实现双向发送消息以及接收消息,需要浏览器和服务器握手进行建立连接。

    http:只能实现客户端请求服务器响应的单向通信,浏览器向服务器发起连接,服务器预先不知道这个连接。

  • 实际应用

    1. 对 websocket 进行封装

      class WebSocketClient {
          constructor(url) {
              this._url = url
              this._callbacks = {};
              this._reconnectTimer = null;
              this.init();
          }
      ​
          init() {
              this._ws = new WebSocket(this._url);
              this._ws.onopen = () => {
                  this.onopen();
              };
              this._ws.onmessage = (e) => {
                  this.onmessage(e);
              };
              this._ws.onclose = (e) => {
                  if (e.code != 1000) {  // 状态码:1000 正常关闭,不重新建立连接
                      this.onclose(e);
                      // 尝试重连
                      this.reconnect();
                  }
              }
          }
      ​
          onopen() {
              console.log('WebSocket open: ', this._url);
          }
      ​
          onmessage(e) {
              console.log('WebSocket message:', e.data);
              if (e.data) {
                  const data = JSON.parse(e.data);
                  const type = 'message';
                  if (type in this._callbacks) {
                      this._callbacks[type](data);
                  }
              }
          }
      ​
          onclose(e) {
              console.log('WebSocket close:', e);
          }
      ​
          reconnect() {
              clearTimeout(this._reconnectTimer);
              this._reconnectTimer = setTimeout(() => {
                  console.log('WebSocket reconnect:', this._url);
                  this.init();
              }, 5000);
          }
      ​
          send(data) {
              if (this._ws.readyState === WebSocket.OPEN) {
                  console.log('WebSocket send:', JSON.stringify(data));
                  this._ws.send(JSON.stringify(data));
              }
          }
      ​
          registerCallback(type, callback) {
              this._callbacks[type] = callback;
          }
      }
      ​
      export default WebSocketClient;
      
    2. 建立 websocket 连接

      <template>
          <button @click="sendMsg">发送消息</button>
          <button @click="disconnect">断开连接</button>
      </template>
      
      <script>
      import WebSocketClient from '@/utils/websocket';   // 看个人需求选择全局引入或按需引入
      
      export default {
          data() {
              return {
                  ws: null,  // 实例
                  messageList: [],  // 消息列表
              }
          },
          methods: {
              // 发送消息
              sendMsg() {
                  this.ws.send({
                      msg: 'hello~'
                  })
              },
              // 断开连接并销毁实例
              disconnect() {
                  this.ws.close()
                  this.ws = null
              }
          },
          created() {
              // 创建实例
              this.ws = new WebSocketClient('ws://localhost:8080');  // 后端提供 websocket 地址或者自己搭建 websocket 服务器
              // 注册消息类型回调函数
              this.ws.registerCallback('message', (data) => {
                  // 存放消息列表
                  this.messageList.push(data)
              });
          }
      }
      </script>