简体   繁体   English

我的私人消息不适用于socket.io

[英]My private messaging doesn't work with socket.io

I can't understand why my code (below) doesn't work. 我不明白为什么我的代码(下面)不起作用。 The console.log prints the correct socket.id on the server-side, before emitting to the socket. 在发送到套接字之前,console.log在服务器端打印正确的socket.id。 So why isn't the message received? 那么为什么没有收到消息呢?

server-side: 服务器端:

socket.on("connectToUser", function(userName, currentUserName, userID){
        console.log("user wants to connect to: ",userID);
         socket.to(userID).emit("connectNotification", currentUserName);
    });

client-side: 客户端:

socket.on("connectNotification", function(currentUserName){
        console.log("correct user notified");
        $("#connectToBox").append("Hallo");
    });

Does the socket.id have to be the original one? socket.id是否必须是原始的? I am changing it on connection, like this: 我正在更改连接,如下所示:

 socket.on('connection', function(socket){ console.log('a user connected', socket.id); var id = uuid.v4(); socket.id = id; console.log(socket.id); 

Changing socket.id after the connection event has fired is probably too late, because at that point, socket.io has already done some internal housekeeping based on the original id. 在触发connection事件后更改socket.id可能为时已晚,因为到那时, socket.io已经根据原始ID进行了一些内部整理。

If you want to use your own id's, you should use a middleware function instead (disclaimer: I'm not overly familiar with the internals of socket.io , but some example code I put together seems to work): 如果您想使用自己的ID,则应改用中间件功能 (免责声明:我对socket.io的内部知识不太熟悉,但我放在一起的一些示例代码似乎可以正常工作):

let server = require('socket.io')(...);

server.use(function(socket, next) {
  socket.id = uuid.v4();
  next();
}).on('connection', function(socket) {

  socket.on("connectToUser", function(userName, currentUserName, userID){
    console.log("user wants to connect to: ",userID);
    socket.to(userID).emit("connectNotification", currentUserName);
  });

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM