前端开启websocket通信

OpenWebSocket () {
      let that = this
      if ("WebSocket" in window) {
       
        if (!isReconnect) {
          this.wsMsg = "正在尝试连接服务器..."
        }
        this.ws = new WebSocket('此处是socket的链接地址');

        let ws = this.ws
        this.ws.onopen = function () {
          console.log('打开ws');
          ws.send('ws send message');
        };

        this.ws.onmessage = function () {
          console.log('接收ws');
        };

        this.ws.onclose = function (e) {
          if (e.wasClean) {
            console.log('关闭socket');
          } else {
            console.log('异常关闭socket');
          }
        };

        this.ws.onerror = function (e) {
          console.log('socket err');
        };
      } else {
        alert("您的浏览器不支持 WebSocket!");
      }
    }

你可能感兴趣的:(前端,websocket,前端,网络协议)