在断开事件中重新连接套接字

我试图重新连接套接字之后断开连接事件被触发相同的socket.id这里是我的套接字configuration

var http = require('http').Server(app); var io = require('socket.io')(http); var connect_clients = [] //here would be the list of socket.id of connected users http.listen(3000, function () { console.log('listening on *:3000'); }); 

所以在断开连接事件,我想重新连接断开连接的用户与相同的socket.id,如果可能的话

 socket.on('disconnect',function(){ var disconnect_id = socket.id; //i want reconnect the users here }); 

默认情况下,Socket.IO没有用于重新连接的服务器端逻辑。 这意味着每次客户端想要连接,一个新的套接字对象被创build,因此它有一个新的ID。 这是由你来实现重新连接。

为了做到这一点,你需要一种方法来存储这个用户的东西。 如果您有任何forms的身份validation(例如护照) – 使用socket.request您将在发生升级之前触发初始HTTP请求。 所以从那里,你可以有所有types的cookie和数据已经存储。

如果您不想在cookies中存储任何内容,最简单的方法就是发回给客户关于他自己的特定信息。 然后,当用户尝试重新连接时,再次发送此信息。 就像是:

 var client2socket = {}; io.on('connect', function(socket) { var uid = Math.random(); // some really unique id :) client2socket[uid] = socket; socket.on('authenticate', function(userID) { delete client2socket[uid]; // remove the "new" socket client2socket[userID] = socket; // replace "old" socket }); }); 

请记住,这只是一个示例,你需要实现一些更好的东西:)也许发送信息作为请求参数,或以另一种方式存储 – 无论为您工作。