使用soocket.io将消息发送到特定客户端,而套接字ID迅速变化

时间:2019-11-11 00:47:49

标签: node.js socket.io

我正在使用node.js和套接字运行聊天服务器,并希望将消息发送到特定客户端。我使用socket.id将消息发送给已定义的用户,例如:

io.sockets.in(user socket.id).emit('message',message)

但是有一个问题: 用户保持连接状态,但套接字ID迅速更改(大约每秒一次),所以我无法使用socket.id。我尝试使用socket.join(用户电子邮件)来使用用户电子邮件而不是套接字ID,但是在套接字ID更改后它不起作用更多。 解决此问题的最佳方法是什么?session-id?如果是,如何聊天客户端应用程序在android设备上运行。 这是我的代码:

io.on("connection", function(socket) {

socket.on("login", function(useremail) {
 socket.join(useremail);
});

//Here i want to send message to specific user
socket.on('messagedetection', (senderNickname,messageContent,targetuser) => {

    //create a message object 
   let  message = {"message":messageContent, "senderNickname":senderNickname}

   //targetuser is the email of target user,joined to the socket in login 
   io.sockets.in(targetuser).emit('message',message)
  });
  socket.on('disconnect', function() {
console.log( ' user has left ')
socket.broadcast.emit("userdisconnect"," user has left ") });

1 个答案:

答案 0 :(得分:0)

让我的评论成为答案,因为这确实是一个问题:

要解决的问题是快速断开/重新连接客户端。这清楚地表明配置中的某些内容不正确。

可能是网络基础结构未正确配置以允许持久的socket.io/webSocket连接。或者,如果您的系统是群集的,则可能是由于非粘性负载平衡引起的。

因此,每次网络基础结构关闭连接时,客户端socket.io库都会尝试重新连接,从而为新连接创建新ID。