websocket 断线重连

websocket 断线重连

服务端为swoole 的websocket

客户端js代码:

//1.创建websocket客户端
  var wsServer = 'ws://ip/';
  var limitConnect = 3;  // 断线重连次数
  var timeConnect =0;
  webSocketInit(wsServer);

  //socket初始化
  function webSocketInit(service){
    var ws = new WebSocket(service);
    ws.onopen = function () {
      console.log("已连接TCP服务器");
    };
    ws.onmessage = function (msg) {
      console.log(msg);
    };
    ws.onclose = function () {
      console.log('服务器已经断开');
      reconnect(service);
    };
    ws.onerror = function (err) {
      //console.log("服务器报错:");
      reconnect(service);
    };

    // 重连
    function reconnect(service) {
      // lockReconnect加锁,防止onclose、onerror两次重连
      if(limitConnect>0){
        if(localStorage.getItem('lockReconnect')!=true){
          localStorage.setItem("lockReconnect",1);
          limitConnect --;
          timeConnect ++;
          console.log("第"+timeConnect+"次重连");
          // 进行重连
          setTimeout(function(){
            webSocketInit(service);
            localStorage.removeItem("lockReconnect");
          },2000);
        }
      }else{
        console.log("TCP连接已超时");
      }
    }

    // 心跳 * 回应
    setInterval(function(){
      websocket.send('');
    }, 1000*100);

注意:

1.onclose、onerror出现两个,tcp重连的时候会重连两次;为避免这种情况,需要进行加锁lockReconnect

2.limitConnect 断线重连次数;timeConnect从0次开始播报

效果:

完整代码:去掉了onerror,不需要加锁

//1.创建websocket客户端
  var wsServer = 'ws://ip/';
  var limitConnect = 3;  // 断线重连次数
  var timeConnect = 0;
  webSocketInit(wsServer);

  //socket初始化
  function webSocketInit(service){
    var ws = new WebSocket(service);
    ws.onopen = function () {
      console.log("已连接TCP服务器");
    };
    ws.onmessage = function (msg) {
      console.log(msg);
    };
    ws.onclose = function () {
      console.log('服务器已经断开');
      reconnect(service);
    };

    // 重连
    function reconnect(service) {
      // lockReconnect加锁,防止onclose、onerror两次重连
      if(limitConnect>0){
          limitConnect --;
          timeConnect ++;
          console.log("第"+timeConnect+"次重连");
          // 进行重连
          setTimeout(function(){
            webSocketInit(service);
          },2000);

      }else{
        console.log("TCP连接已超时");
      }
    }

    // 心跳 * 回应
    setInterval(function(){
      websocket.send('');
    }, 1000*100);

原文链接: https://www.cnblogs.com/wesky/p/12111929.html

Comments are closed.