使用websockets处理连接丢失

0g0grzrc  于 2023-08-05  发布在  其他
关注(0)|答案(6)|浏览(161)

我最近设置了一个工作正常的本地WebSocket服务器,但是我在理解如何处理客户端或服务器都没有故意启动的突然连接丢失时遇到了一些麻烦,即:服务器断电、以太网电缆被拔出等...我需要客户端的知道是否连接已在~ 10秒内丢失。
客户端,连接简单:

var websocket_conn = new WebSocket('ws://192.168.0.5:3000');

websocket_conn.onopen = function(e) {
    console.log('Connected!');
};

websocket_conn.onclose = function(e) {
    console.log('Disconnected!');
};

字符串
我可以手动断开连接,

websocket_conn.close();


但是如果我只是简单地从计算机后面拔出以太网电缆,或者禁用连接,onclose就不会被调用。我在另一篇文章中读到,它最终会在TCP detects loss of connectivity时被调用,但它不是我需要的及时方式,因为我相信Firefox的默认时间是10分钟,我真的不想在数百台计算机about:config上更改这个值。我读到的唯一的其他建议是使用“ping/pong”保持活动轮询风格的方法,这似乎与websockets的想法相反。
有没有更简单的方法来检测这种断开连接行为?我正在阅读的旧帖子从技术Angular 来看仍然是最新的吗?最好的方法仍然是“乒乓”风格?

iq0todco

iq0todco1#

需要增加乒乓方法

当接收到**ping发送回pong**时,在服务器中创建代码
JavaScript代码给予

function ping() {
        ws.send('__ping__');
        tm = setTimeout(function () {

           /// ---connection closed ///

    }, 5000);
}

function pong() {
    clearTimeout(tm);
}
websocket_conn.onopen = function () {
    setInterval(ping, 30000);
}
websocket_conn.onmessage = function (evt) {
    var msg = evt.data;
    if (msg == '__pong__') {
        pong();
        return;
    }
    //////-- other operation --//
}

字符串

r1zk6ea1

r1zk6ea12#

这是我最终做的解决方案,目前看起来工作得很好,它完全特定于我的项目设置,依赖于我的问题中最初没有提到的标准,但如果其他人碰巧在做同样的事情,它可能会很有用。
与WebSocket服务器的连接发生在Firefox插件中,默认情况下Firefox的TCP设置有10分钟的超时。您可以通过about:config和搜索TCP查看更多详细信息。
Firefox插件可以访问这些参数

var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService);

字符串
并通过指定分支& preference沿着新值来更改这些参数

prefs.getBranch("network.http.tcp_keepalive.").setIntPref('long_lived_idle_time', 10);


所以现在,任何安装了插件的计算机都有10秒的TCP连接超时。如果连接丢失,则会触发onclose事件,该事件将显示警报并尝试重新建立连接

websocket_conn.onclose = function (e) {
    document.getElementById('websocket_no_connection').style.display = 'block';
    setTimeout(my_extension.setup_websockets, 10000);
};

dffbzjpn

dffbzjpn3#

我使用了乒乓球的想法,它工作得很好。下面是我在server.js文件中的实现:

var SOCKET_CONNECTING = 0;
var SOCKET_OPEN = 1;
var SOCKET_CLOSING = 2;
var SOCKET_CLOSED = 3;

var WebSocketServer = require('ws').Server
wss = new WebSocketServer({ port: 8081 });

//Send message to all the users
wss.broadcast = function broadcast(data,sentBy)
{
  for (var i in this.clients)
  {
    this.clients[i].send(data);
  }
};

var userList = [];
var keepAlive = null;
var keepAliveInterval = 5000; //5 seconds

//JSON string parser
function isJson(str)
{
 try {
    JSON.parse(str);
  }
  catch (e) {
    return false;
  }
  return true;
}

//WebSocket connection open handler
wss.on('connection', function connection(ws) {
  
  function ping(client) {
    if (ws.readyState === SOCKET_OPEN) {
      ws.send('__ping__');
    } else {
      console.log('Server - connection has been closed for client ' + client);
      removeUser(client);
    }
  }
  
  function removeUser(client) {
    
    console.log('Server - removing user: ' + client)
    
    var found = false;
    for (var i = 0; i < userList.length; i++) {
      if (userList[i].name === client) {
        userList.splice(i, 1);
        found = true;
      }
    }
    
    //send out the updated users list
    if (found) {
      wss.broadcast(JSON.stringify({userList: userList}));
    };
    
    return found;
  }
  
  function pong(client) {
    console.log('Server - ' + client + ' is still active');
    clearTimeout(keepAlive);
    setTimeout(function () {
      ping(client);
    }, keepAliveInterval);
  }

  //WebSocket message receive handler
  ws.on('message', function incoming(message) {
    if (isJson(message)) {
      var obj = JSON.parse(message);
      
      //client is responding to keepAlive
      if (obj.keepAlive !== undefined) {
        pong(obj.keepAlive.toLowerCase());
      }
      
      if (obj.action === 'join') {
        console.log('Server - joining', obj);
        
        //start pinging to keep alive
        ping(obj.name.toLocaleLowerCase());
        
        if (userList.filter(function(e) { return e.name == obj.name.toLowerCase(); }).length <= 0) {
          userList.push({name: obj.name.toLowerCase()});
        }
        
        wss.broadcast(JSON.stringify({userList: userList}));
        console.log('Server - broadcasting user list', userList);
      }
    }
    
    console.log('Server - received: %s', message.toString());
    return false;
  });
});

字符串
下面是我的index.html文件:

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
        <title>Socket Test</title>
    </head>
    <body>
        <div id="loading" style="display: none">
            <p align="center">
                LOADING...
            </p>
        </div>
        <div id="login">
            <p align="center">
                <label for="name">Enter Your Name:</label>
                <input type="text" id="name" />
                <select id="role">
                    <option value="0">Attendee</option>
                    <option value="1">Presenter</option>
                </select>
                <button type="submit" onClick="login(document.getElementById('name').value, document.getElementById('role').value)">
                    Join
                </button>
            </p>
        </div>
        <div id="presentation" style="display: none">
            <div class="slides">
                <section>Slide 1</section>
                <section>Slide 2</section>
            </div>
            <div id="online" style="font-size: 12px; width: 200px">
                <strong>Users Online</strong>
                <div id="userList">
                </div>
            </div>
        </div>
        <script>
            function isJson(str) {
                try {
                   JSON.parse(str);
                }
                catch (e) {
                   return false;
                }
                return true;
            }

            var ws;
            var isChangedByMe = true;
            var name = document.getElementById('name').value;
            var role = document.getElementById('role').value;

            function init()
            {
                loading = true;
                ws = new WebSocket('wss://web-sockets-design1online.c9users.io:8081');

                //Connection open event handler
                ws.onopen = function(evt)
                {
                    ws.send(JSON.stringify({action: 'connect', name: name, role: role}));
                }

                ws.onerror = function (msg) {
                    alert('socket error:' + msg.toString());
                }

                //if their socket closes unexpectedly, re-establish the connection
                ws.onclose = function() {
                    init();
                }
                
                //Event Handler to receive messages from server
                ws.onmessage = function(message)
                {
                    console.log('Client - received socket message: '+ message.data.toString());
                    document.getElementById('loading').style.display = 'none';

                    if (message.data) {

                        obj = message.data;
                    
                        if (obj.userList) {
                        
                            //remove the current users in the list
                            userListElement = document.getElementById('userList');
                            
                            while (userListElement.hasChildNodes()) {
                                userListElement.removeChild(userListElement.lastChild);
                            }

                            //add on the new users to the list
                            for (var i = 0; i < obj.userList.length; i++) {
                            
                                var span = document.createElement('span');
                                span.className = 'user';
                                span.style.display = 'block';
                                span.innerHTML = obj.userList[i].name;
                                userListElement.appendChild(span);
                            }
                        }
                    }

                    if (message.data === '__ping__') {
                        ws.send(JSON.stringify({keepAlive: name}));
                    }

                    return false;
                }
            }

            function login(userName, userRole) {

                if (!userName) {
                    alert('You must enter a name.');
                    return false;
                } 

                //set the global variables
                name = userName;
                role = userRole;

                document.getElementById('loading').style.display = 'block';
                document.getElementById('presentation').style.display = 'none';
                document.getElementById('login').style.display = 'none';
                init();
            }
        </script>
    </body>
</html>


这里有一个链接到云9沙盒,如果你想尝试一下自己:https://ide.c9.io/design1online/web-sockets

qoefvg9y

qoefvg9y4#

WebSocket协议定义了ping和pong的控制帧。因此,基本上,如果服务器发送ping,浏览器将以pong应答,并且它也应该以相反的方式工作。也许你使用的WebSocket服务器实现了它们,你可以定义一个超时,在这个超时内浏览器必须响应或者被认为是死的。这对于浏览器和服务器中的实现都应该是透明的。
您可以使用它们来检测半开连接:http://blog.stephencleary.com/2009/05/detection-of-half-open-dropped.html
还相关:WebSockets ping/pong, why not TCP keepalive?

mhd8tkvw

mhd8tkvw5#

好吧,我迟到了,但希望我能在这里增加一些价值。我在Angular应用程序中的TypeScript实现用于处理WebSocket连接丢失。这不使用PING PONG策略,以避免让服务器一直处于忙碌状态。只有在连接丢失后才开始尝试建立连接,并在每5秒后继续尝试,直到连接成功。我们开始吧

export class WebSocketClientComponent implements OnInit {

   webSocket?: WebSocket;
   selfClosing = false;
   reconnectTimeout: any;

   ngOnInit(): void {
      this.establishWebSocketConnection();
   }

   establishWebSocketConnection() {

      this.webSocket = new WebSocket('YourServerURlHere');
 
      this.webSocket.onopen = (ev: any) => {
  
         if (this.reconnectTimeout) {
            clearTimeout(this.reconnectTimeout);
         }
      }

      this.webSocket.onclose = (ev: CloseEvent) => {
  
         if (this.selfClosing === false) {
            this.startAttemptingToEstablishConnection();
         }
      }
   }

   private startAttemptingToEstablishConnection() {
      this.reconnectTimeout = setTimeout(() => this.establishWebSocketConnection(), 5000);
   }
}

字符串
就是这样。如果你想在某个时候关闭WebSocket连接,请设置selfClosing = true。这将停止再次尝试重新连接。希望这对你有帮助。我敢肯定,同样的代码也可以在原生JS中使用。

9jyewag0

9jyewag06#

您可以用途:
window.addEventListener(“offline”,closeHandler)//在断开LAN连接后1秒内为我工作
代码:
const createChannel =()=> {
ws && closeChannelCommon()
ws = new WebSocket(“wss:social-network.samuraijs.com/handlers/ChatHandler.ashx“)
ws?.addEventListener('open',openHandler)
ws?.addEventListener('message',messageHandler)
ws?.addEventListener('close',closeHandler)
window.addEventListener('offline',closeHandler)
}
const closeHandler =()=> {console.log(“网络连接已丢失。”);}

相关问题