简体   繁体   中英

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. 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? 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.

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):

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

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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