node.js doesn't send socket on disconnect event

走远了吗. 提交于 2019-12-04 00:42:21

问题


When someone connects to the node server, I keep an array with all the sockets. That way I can broadcast messages to everyone whenever that is needed or loop through the users to count the number of online users, etc.

All this works fine, but when a on disconnect event is fired, I don't receive a socket in my arguments. Is there another way to know which socket just disconnected?

var allClients = [];

io.sockets.on('connection', function(socket) {
   allClients.push(socket);

   socket.on('disconnect', function(socket) {
      console.log('Got disconnect!');

      var i = allClients.indexOf(socket);
      delete allClients[i];
   });
});

Of course the above example doesn't work, because disconnect event doesn't give a socket argument (or any other argument). So is there another event that fired before a disconnect where the socket is still there?

Ali


回答1:


You already have the socket, because the disconnect handler is declared within the 'connection' event scope. Try removing the parameter you are passing to the 'disconnect' handler, you should be able to work with the socket parameter from the connection handler.

io.sockets.on('connection', function(socket) {
   allClients.push(socket);

   socket.on('disconnect', function() {
      console.log('Got disconnect!');

      var i = allClients.indexOf(socket);
      delete allClients[i];
   });
});

Apart from that, you don't need a socket array to broadcast, you can use rooms to group sockets and broadcast to all the sockets inside that room.



来源:https://stackoverflow.com/questions/9868846/node-js-doesnt-send-socket-on-disconnect-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!