我正在为我们的网站做一个应用程序,用户可以互相发送聊天信息。我使用nodejs和socketio成功地做到了这一点。我有一个具有某种通知图标的标题,就像facebook一样,可以在所有页面中看到。现在,如果用户打开多个选项卡并收到一条消息,那么所有打开的选项卡都会看到图标亮起。通过跟踪用户通过2D套接字数组打开的套接字连接,我就可以做到这一点:
var container = {};
io.sockets.on( 'connection', function(client) {
client.on('set account online', function(username) {
if (!(username in container)) {
console.log(username + " is now Online" );
container[username] = [];
}
client.username = username;
container[username].push(client);
});
client.on('set account offline', function(username) {
if (username in container) {
delete container[username];
console.log(username + " is now Offline" );
}
});然后,当发送消息时,我遍历适当的数组元素。
client.on('send message', function(data) {
if (data.recipient in container) {
var clients = container[data.recipient];
for(var i = 0; i < clients.length;i++){
clients[i].emit('send message', {recipient: data.recipient, message: data.message });
}
}
});这一切都运行得很好(但不确定它编码得有多好)。问题是,如果用户关闭一个选项卡,该选项卡的套接字仍然存在于container变量中,并且如果收到该特定用户的消息,节点仍将尝试发出该套接字。此外,它只是感觉更干净,不跟踪任何断开的插座。
我一直在考虑这个问题,我认为我必须将套接字断开事件绑定到客户端的onbeforeunload事件,我们都知道这在不同的浏览器中是如何执行的。对于如何将断开连接的套接字从container数组中拼接,有什么建议吗?
发布于 2015-01-30 11:21:57
根据我的评论:
你真的应该在执行室。在每个连接上,每个用户都应该加入他们自己的房间,来自同一用户的任何其他连接都应该加入这个房间。然后,您可以向房间发送数据,其中的每个客户端都将接收数据。
您的代码可以更改为:
io.sockets.on('connection', function(client) {
client.on('set account online', function(username) {
client.join(username);
});
client.on('set account offline', function(username) {
client.leave(username);
});
client.on('send message', function(data) {
io.to(data.recipient).emit('send message', {
recipient: data.recipient,
message: data.message
});
});
});https://stackoverflow.com/questions/28234387
复制相似问题