node.js 在断开连接事件时不发送套接字 [英] node.js doesn't send socket on disconnect event

查看:26
本文介绍了node.js 在断开连接事件时不发送套接字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当有人连接到节点服务器时,我会保留一个包含所有套接字的数组.这样我就可以在需要的时候向所有人广播消息,或者遍历用户以计算在线用户的数量等.

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];
   });
});

当然上面的例子不起作用,因为 disconnect 事件没有给出套接字参数(或任何其他参数).那么在套接字仍然存在的断开连接之前是否触发了另一个事件?

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?

阿里

推荐答案

您已经有了套接字,因为断开连接处理程序是在 'connection' 事件范围内声明的.尝试删除您传递给断开连接"处理程序的参数,您应该能够使用连接处理程序中的套接字参数.

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.

这篇关于node.js 在断开连接事件时不发送套接字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆