• 【网络通信】websocket如何断线重连


    Vue

    <template>
      <div>
        <button @click="sendDevName('xxxxxxxx')">发送</button>
        {{data}}
      </div>
    </template>
    
    <script>
    export default {
      name: 'HelloWorld',
      data () {
        return {
          data: null
        }
      },
      // html加载完成后执行initWebSocket()进行websocket初始化
      mounted () {
        this.initWebSocket()
      },
      // 离开该层时执行,划重点了!!!
      destroyed: function () {
        // 离开路由之后断开websocket连接
        this.websock.close()
      },
      methods: {
        // 初始化websocket
        initWebSocket () {
          const path = 'ws://xxx.xxx.xxx.xxx:端口号/xxxxx'// 后台给的websocket的ip地址
          this.websock = new WebSocket(path)
          this.websock.onmessage = this.websocketOnMessage
          this.websock.onopen = this.websocketOnOpen
          this.websock.onerror = this.websocketOnError
          this.websock.onclose = this.websocketClose
        },
        // 连接建立成功的信号
        websocketOnOpen () {
          console.log('初始化成功')// 连接成功后就可以在这里写一些回调函数了
        },
        // 连接建立失败重连
        websocketOnError () {
          // 如果报错的话,在这里就可以重新初始化websocket,这就是断线重连
          this.initWebSocket()
        },
        // 数据接收
        websocketOnMessage (e) {
          console.log(e)// e这个变量就是后台传回的数据,在这个函数里面可以进行处理传回的值
          this.data = e// 这边我绑定了一个data,data会在网页上显示后端传来的东西
        },
        // 数据发送
        websocketSend (Data) {
          this.websock.send(Data)// Data变量就是你想对后台说些啥,根据后端给你的接口文档传值进行交互
        },
        // 关闭的信号
        websocketClose () {
          console.log('断开连接')
        },
        // 传参给后端,这里对websocketSend又进行了一层封装,用不到的可以删除
        sendDevName (chooseDevice) {
          console.log(chooseDevice)
          this.websocketSend(chooseDevice)
        }
      }
    }
    </script>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65

    前端点击“发送”后端服务器就会接受到马赛克里面的东西
    在这里插入图片描述前端点击发送按钮触发websocketSend (Data)函数后端就会收到前端发的消息,根据前端传过来的消息再发送前端所需要的信息,前端一旦监听到有东西发过来就会触发websocketOnMessage (e)这个函数

    websocket的状态

    ebsocket的两个属性:readyState和bufferedAmount。
    根据readyState属性可以判断webSocket的连接状态,该属性的值可以是下面几种:
    0 :对应常量CONNECTING (numeric value 0),
    正在建立连接连接,还没有完成。The connection has not yet been established.
    1 :对应常量OPEN (numeric value 1),
    连接成功建立,可以进行通信。The WebSocket connection is established and communication is possible.
    2 :对应常量CLOSING (numeric value 2)
    连接正在进行关闭握手,即将关闭。The connection is going through the closing handshake.
    3 : 对应常量CLOSED (numeric value 3)
    连接已经关闭或者根本没有建立。The connection has been closed or could not be opened.
    例:
    var socket = new WebSocket(url);
    if(socket.readyState!=1){
    alert(“未连接。”);
    return;
    }
    根据bufferedAmount可以知道有多少字节的数据等待发送,若websocket已经调用了close方法则该属性将一直增长。

    Js

    首先我们要熟悉如下几个api

    1、连接websocket的服务器的websocekt函数

    2、websocekt断开后触发的onclose函数

    由上面这两个函数就可以了,大致思路梳理一下:

    1、首先开发一个函数websocketinit,函数主要是websocket的连接逻辑,监听信息,发送信息

    2、监听onclose事件,onclose触发后重新执行websocketinit事件

    思路有了大致代码如下:

      function webSocketInit(service){
       //1、初始化ws
       //2、监听onclose事件 重新执行websocketInit函数
      }
    
    • 1
    • 2
    • 3
    • 4

    具体代码如下:

    //1.创建websocket客户端
    var host = window.location.host; #IP
    var ut = "{{ ut }}";
    var wsServer = 'wss://' + host + '/notify/wxlogin?ut=' + ut;
    
    var timeConnect = 0;
    webSocketInit(wsServer);
    
    //socket初始化
    function webSocketInit(service) {
        var ws = new WebSocket(service);
        ws.onopen = function () {
            console.log("已连接TCP服务器");
            ws.send('Hello WebSockets!');
    
        };
        ws.onmessage = function (evt) {
            console.log('Received Message: ' + evt.data);
    
            data = JSON.parse(evt.data);
            console.log(data);
            if (data.status != 0) {
                alert("扫码错误");
                ws.close();
            }
            if (data.data.wx_login == 1) {
                //window.location.href = "http://" + host + "/admin"
                window.location.href = "/admin"
    
            }
            if (data.data.wx_login == 0) {
                //alert(data.data.message)
                $(".qr_code").css("display", "none");
                $(".tips").text(data.data.message)
    
            }
            console.log(data.data);
        };
    
        ws.onclose = function () {
            console.log('服务器已经断开');
            reconnect(service);
        };
    }
    
    // 重连
    function reconnect(service) {
        // lockReconnect加锁,防止onclose、onerror两次重连
        timeConnect++;
        console.log("第" + timeConnect + "次重连");
        // 进行重连
        setTimeout(function () {
            webSocketInit(service);
        }, 1000);
    
    }
    
    
    // 心跳 * 回应
    setInterval(function () {
        var websocket = new WebSocket(wsServer);
        websocket.send('');
    
    }, 1000 * 100)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64

    来源

    vue实现websocket断线重连
    websocket断线重连的方法

  • 相关阅读:
    基于FPGA双路GMSL接收
    应广单片机实现红蓝双色爆闪灯
    ZIP压缩文件的打开密码和自动加密有什么不同?
    UUCTF WP
    Nacos安装讲解教程
    常说的I2C协议是干啥的(电子硬件)
    【WLAN】Android 13 WIFI 连接流程
    ssm项目环境初步搭建
    【精通内核】Linux 内核写锁实现原理与源码解析
    第一个2DGodot游戏-从零开始-逐步解析
  • 原文地址:https://blog.csdn.net/weixin_44231544/article/details/126619809