我一直在阅读有关此问题的答案已有一段时间了,但这些解决方案似乎都不适用于我的设置。
我有一个nodeJS服务器和express一起使用。我使用Socket.io向个人用户发送通知。 (前端是Angular)
当用户登录时,他加入以他的电子邮件地址命名的房间(唯一)。
join
当用户登录时,io.sockets.in(to).emit('notification', {
message: msg,
source: from,
destination: to,
event: data
});
事件将从角度广播。
这样我只需使用电子邮件地址即可发送通知:
socket.on('leave', function(user) {
//remove the user from the list
var index = findUserConnected(socket.id);
if(index != null) {
connected_users.splice(index, 1);
}
socket.leave(user.email);
});
当用户手动注销时,我注册了以下事件监听器:
disconnect
最后,只要用户注销或刷新页面,就会有socket.on('disconnect', function() {
//if the user refreshes the page, he is still in the connected users list
var email = findEmailUserConnected(socket.id);
if(email != null) {
//we make him join back his room
socket.join(email);
}
});
处理程序:
io.sockets.in(email).emit('notification', {});
从技术上讲这是有效的。在页面刷新时,用户加入他的房间。
问题仅在页面刷新时,即使用户在他的房间内,也不会收到使用socket.disconnect()
发送的通知。
显然页面刷新调用{{1}}会生成一个新的socket_id。我不确定是否有办法将socket_id重新分配给房间或类似的东西。
答案 0 :(得分:1)
好的,首先接受'断开'服务器上的事件意味着该套接字上的连接将终止。因此,没有必要像现在这样在同一个房间中使用相同的套接字连接。
.env.sample
我的建议是确保每次建立新连接时用户始终加入房间(电子邮件)。可以通过在每个新连接上添加发送join事件来轻松完成。 在您的客户端代码中
socket.on('disconnect', function() {
var email = findEmailUserConnected(socket.id);
if(email != null) {
socket.join(email); // this would never work because this socket connection is not going to exist anymore.
}
});
这样可以确保无论何时建立新连接,都会将加入事件发送到服务器和' socket.on(' join',...)'服务器中的监听器会将新套接字添加到房间。希望这会有所帮助:)