Reputation: 206
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);
Upvotes: 0
Views: 157
Reputation: 203231
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);
});
});
Upvotes: 1