当我使用socket.io时,断开连接没有发生(仅当我手动关闭服务器时)。但是您可以在例如失败10秒或发生断开事件后说几秒钟后重新连接。
@H_404_5@socket.on('disconnect', function(){ // reconnect });
我想出了以下实现:
@H_404_5@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 connection socket.connect(); retryConnectOnFailure(RETRY_INTERVAL);
@H_404_5@// express route to ping server. app.get('/ping', function(req, res) { res.send('pong'); });