码迷,mamicode.com
首页 > Web开发 > 详细

websocket 断线重连

时间:2019-12-28 16:37:42      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:func   img   js代码   sock   info   图片   bsp   次数   close   

服务端为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);

 

websocket 断线重连

标签:func   img   js代码   sock   info   图片   bsp   次数   close   

原文地址:https://www.cnblogs.com/wesky/p/12111929.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!