websocket

作者: 哼_ | 来源:发表于2022-01-07 14:27 被阅读0次

一、创建websocket 实例

WebSocket 对象作为一个构造函数,用于新建 WebSocket 实例。

var Socket = new WebSocket(url,[protocol]);

以上代码用于创建 WebSocket 对象,其中的第一个参数 url, 即为指定连接的 URL。第二个参数 protocol 是可选的,指定了可接受的子协议。一般来说,大多没有具体要求的,就只用写url即可。
二、websocket 属性
例如: var ws = new WebSocket('ws://1xx.xxx.xxx.xxx:8080/ws'); 打印出创建的socket对象,内容如下,这些也正是websocket的属性。

binaryType: "blob"  //返回websocket连接所传输二进制数据的类型,如果传输的是Blob类型的数据,则为"blob",如果传输的是Arraybuffer类型的数据,则为"arraybuffer"
  bufferedAmount: 0   //为只读属性,用于返回已经被send()方法放入队列中但还没有被发送到网络中的数据的字节数。
  extensions: ""
  onclose: ƒ ()    //连接关闭时触发
  onerror: ƒ ()   //通信发生错误时触发
  onmessage: ƒ (e)    //客户端接收服务端数据时触发,e为接受的数据对象
  onopen: ƒ ()    //连接建立时触发
  protocol: ""  //用于返回服务器端选中的子协议的名字;这是一个在创建websocket对象时,在参数protocols中指定的字符串。
  readyState: 1   //返回值为当前websocket的链接状态
  url: "ws://1xx.xxx.xxx.xxx:8080/ws"    //返回值为当构造函数创建WebSocket实例对象时URL的绝对路径。

所有属性讲解清单:https://developer.mozilla.org/en-US/docs/Web/API/WebSocket

三、方法

假定我们使用了上述代码创建的websocket对象,下面两个方法可以在任意socket事件中调用,根据自己项目需求而定。

ws.send() :使用连接发送数据,可以发送你想要发送的各种类型数据,如Blob对象、ArrayBuffer 对象、基本或复杂的数据类型等;

ws.send('消息');
//发送对象需要格式转换,接受数据同理
ws.send(JSON.stringify(data));
ws.close() : 关闭连接,用户可以主动调取此方法,来关闭连接。

以上文章参考: https://www.cnblogs.com/songForU/p/12596029.html

以下是自己项目运用到的websocket 技术

  <template>
<div>
这是一个组件内容
</div>
</template>

<script>
  export default {
    name: "",
    components: {},
    data () {
      return {
        websock: null,
        lockReconnect:false,
        heartCheck:nul
      }
    },
    mounted() {
      this.initWebSocket();
      this.heartCheckFun(); 
    },
    destroyed: function () { // 离开页面生命周期函数
      this.websocketclose();
    },
    methods: {
      initWebSocket: function () {
        // WebSocket与普通的请求所用协议有所不同,ws等同于http,wss等同于https
        var userId = store.getters.userInfo.id;
        var url = window._CONFIG['domianURL'].replace("https://","wss://").replace("http://","ws://")+"/websocket/"+userId;
        this.websock = new WebSocket(url);
        this.websock.onopen = this.websocketonopen; // 连接websocket
        this.websock.onerror = this.websocketonerror;// 连接发生错误
        this.websock.onmessage = this.websocketonmessage;// 接收消息
        this.websock.onclose = this.websocketclose;// 关闭连接
      },
      websocketonopen: function () {
        console.log("WebSocket连接成功");//心跳检测重置
        this.heartCheck.reset().start(); // 保活,前端每隔几秒发送消息到后端.
      },
      websocketonerror: function (e) {
        console.log("WebSocket连接发生错误");
        this.reconnect();
      },
      websocketonmessage: function (e) {
        console.log("-----接收消息-------",e.data);
        var data = eval("(" + e.data + ")"); //解析对象
        //心跳检测重置
        this.heartCheck.reset().start();
      },
      websocketsend(text) { // 数据发送
        try {
          this.websock.send(text);
        } catch (err) {
          console.log("send failed (" + err.code + ")");
        }
      },
      websocketclose: function (e) {
        console.log("connection closed (" + e.code + ")");
        this.reconnect();
      },
      reconnect() {
        var that = this;
        if(that.lockReconnect) return;
        that.lockReconnect = true;
        //没连接上会一直重连,设置延迟避免请求过多
        setTimeout(function () {
          console.info("尝试重连...");
          that.initWebSocket();
          that.lockReconnect = false;
        }, 5000);
      },
      heartCheckFun(){
        var that = this;
        //心跳检测,每20s心跳一次
        that.heartCheck = {
          timeout: 10000,
          timeoutObj: null,
          serverTimeoutObj: null,
          reset: function(){
            clearTimeout(this.timeoutObj);
            //clearTimeout(this.serverTimeoutObj);
            return this;
          },
          start: function(){
            var self = this;
            this.timeoutObj = setTimeout(function(){
              //这里发送一个心跳,后端收到后,返回一个心跳消息,
              //onmessage拿到返回的心跳就说明连接正常
              that.websocketsend("HeartBeat");
              console.info("客户端发送心跳");
            }, this.timeout)
          }
        }
      },
    }
  }
</script>

相关文章

网友评论

      本文标题:websocket

      本文链接:https://www.haomeiwen.com/subject/xvkjcrtx.html