Node.js和Socket.IO – 如何断开连接后立即重新连接

我正在用node.js和socket.io构build一个小的原型。 一切工作正常,我面临的唯一问题是,我的node.js连接将断开连接,我被迫刷新页面,以获得连接并再次运行。

一旦断开连接事件被触发,是否有办法重新build立连接?

据我所知,这是一个普遍的问题。 所以,我正在寻找解决这个问题的最佳实践方法:)

丹非常感谢

编辑:现在Socket.io内置支持

当我使用socket.io断开连接没有发生(只有当我手动closures服务器)。 但是你可以重新连接之后说例如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 connection socket.connect(); retryConnectOnFailure(RETRY_INTERVAL); 

服务器端(的node.js):

 // express route to ping server. app.get('/ping', function(req, res) { res.send('pong'); }); 

编辑 :socket.io现在有内置的重新连接支持 。 使用它。

例如(这是默认值):

 io.connect('http://localhost', { 'reconnection': true, 'reconnectionDelay': 500, 'reconnectionAttempts': 10 }); 

这就是我所做的:

 socket.on('disconnect', function () { console.log('reconnecting...') socket.connect() }) socket.on('connect_failed', function () { console.log('connection failed. reconnecting...') socket.connect() }) 

这似乎工作得很好,虽然我只testing了websocket传输。

即使第一次尝试失败,也要开始重新连接

如果第一次连接尝试失败, socket.io 0.9.16不会尝试重新连接的原因。 这是我如何解决这个问题。

 //if this fails, socket.io gives up var socket = io.connect(); //tell socket.io to never give up :) socket.on('error', function(){ socket.socket.reconnect(); }); 

我知道这有一个公认的答案,但我永远searchfind我正在寻找,并认为这可能会帮助别人。

如果你想让你的客户端尝试重新连接无穷大(我需要这样的一个项目,几个客户端将被连接,但我需要他们总是重新连接,如果我把服务器closures)。

 var max_socket_reconnects = 6; var socket = io.connect('http://foo.bar',{ 'max reconnection attempts' : max_socket_reconnects }); socket.on("reconnecting", function(delay, attempt) { if (attempt === max_socket_reconnects) { setTimeout(function(){ socket.socket.reconnect(); }, 5000); return console.log("Failed to reconnect. Lets try that again in 5 seconds."); } });