NodeJS Websocket在服务器重启时如何重新连接

在Node.js中,我使用https://github.com/einaros/ws进行WebSocket连接。 以下是客户端的代码。 假设我们正在连接的服务器套接字下降一分钟。 closures事件将会触发,但是每当服务器上的套接字closures或错误时,重新连接套接字的最佳方法是什么?

var ws = new WebSocket('ws://localhost'); ws.on('open', function() { console.log('socket open'); }); ws.on('error', function() { console.log('socket error'); // how do I reconnect to the ws after x minutes here? }); ws.on('close', function() { console.log('socket close'); // how do I reconnect to the ws after x minutes here? }); 

       

网上收集的解决方案 "NodeJS Websocket在服务器重启时如何重新连接"

我已经成功地使用了https://github.com/joewalnes/reconnecting-websocket/blob/master/reconnecting-websocket.js

你应该可以做到:

 ws = new ReconnectingWebSocket('ws://....'); ws.reconnectInterval = 60000; // try to reconnect after 10 seconds 

尝试这个:

 var reconnectInterval = x * 1000 * 60; var ws; var connect = function(){ ws = new WebSocket('ws://localhost'); ws.on('open', function() { console.log('socket open'); }); ws.on('error', function() { console.log('socket error'); }); ws.on('close', function() { console.log('socket close'); setTimeout(connect, reconnectInterval); }); }; connect(); 

你可以使用原来的实现,而不必包装它。