zoukankan      html  css  js  c++  java
  • Vue项目中使用websocket

    <template>
      <div class="test">
    
      </div>
    </template>
    
    <script>
      export default {
        name : 'test',
        data() {
          return {
            websock: null,
          }
        },
        created() {
          this.initWebSocket();
        },
        destroyed() {
          this.websock.close() //离开路由之后断开websocket连接
        },
        methods: {
          initWebSocket(){ //初始化weosocket
            const wsuri = "ws://127.0.0.1:8080";
            this.websock = new WebSocket(wsuri);
            this.websock.onmessage = this.websocketonmessage;
            this.websock.onopen = this.websocketonopen;
            this.websock.onerror = this.websocketonerror;
            this.websock.onclose = this.websocketclose;
          },
          websocketonopen(){ //连接建立之后执行send方法发送数据
            let actions = {"test":"12345"};
            this.websocketsend(JSON.stringify(actions));
          },
          websocketonerror(){//连接建立失败重连
            this.initWebSocket();
          },
          websocketonmessage(e){ //数据接收
            const redata = JSON.parse(e.data);
          },
          websocketsend(Data){//数据发送
            this.websock.send(Data);
          },
          websocketclose(e){  //关闭
            console.log('断开连接',e);
          },
        },
      }
    </script>
    <style lang='less'>
     
    </style>
    

    要是需要发心跳的话,只需要在onopen里写一个定时器发送心跳即可

    js封装一个websocket

    seven0706-js封装一个websocket

  • 相关阅读:
    暑期测试训练3
    对于在线段树上修改整段区间的理解
    UVA 11090 判负圈问题
    ZOJ 2588 求割边问题
    POJ 1523 网络连通
    hdu 1163
    hdu 1703
    hdu 2577 模拟
    hdu 3836 强连通+缩点:加边构强连通
    hdu 2571
  • 原文地址:https://www.cnblogs.com/kerin/p/15560785.html
Copyright © 2011-2022 走看看