编辑:Socket.io已内置支持现在
当我使用socket.io时,断开连接没有发生(仅当我手动关闭服务器时)。但是您可以在例如失败10秒或发生断开事件后说几秒钟后重新连接。
socket.on('disconnect', function(){ // reconnect});我想出了以下实现:
客户端Javascript
var connected = false;const RETRY_INTERVAL = 10000;var timeout;socket.on('connect', function() { connected = true; clearTimeout(timeout); socket.send({'subscribe': 'schaftenaar'}); content.html("<b>Connected to server.</b>");});socket.on('disconnect', function() { connected = false; console.log('disconnected'); content.html("<b>Disconnected! Trying to automatically to reconnect in " + RETRY_INTERVAL/1000 + " seconds.</b>"); retryConnectOnFailure(RETRY_INTERVAL);});var retryConnectOnFailure = function(retryInMilliseconds) { setTimeout(function() { if (!connected) { $.get('/ping', function(data) { connected = true; window.location.href = unescape(window.location.pathname); }); retryConnectOnFailure(retryInMilliseconds); } }, retryInMilliseconds); }// start connectionsocket.connect();retryConnectOnFailure(RETRY_INTERVAL);服务器端(node.js):
// express route to ping server.app.get('/ping', function(req, res) { res.send('pong');});


