在Node.js中,我将websockets / ws用于WebSocket连接。下面是客户端的代码。假设我们要连接的服务器套接字关闭了一分钟。关闭事件将触发,但是每当服务器上的套接字出现故障或错误时,重新连接到套接字的最佳方法是什么?
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? });
我已经成功使用https://github.com/joewalnes/reconnecting- websocket/blob/master/reconnecting- websocket.js。
您应该能够:
ws = new ReconnectingWebSocket('ws://....'); ws.reconnectInterval = 60000; // try to reconnect after 10 seconds