简体   繁体   中英

Can't send message to only one specific room through node.js and socket.io

I have a problem that i don't seems to be able to solve it. I'm doing some kind of integration with remote system and my code is in iframe but that can't be important for this one i hope :).

I'm trying to send a message from server to specific room/client to begin session. First thing I do is when user log in, I emit message from client side with username.

CLIENT.JS
conn.on('connect', function () {
   conn.emit('session', { username: 'some_username' });
}, false);

And on server side i get message and join socket to the room.

SERVER.JS
socket.on('session', function(session) {
   socket.join(session.username);
});

I have another module that communicates with this server.js script through redis. So i have two more events in server.js

SERVER.JS
var userCreate = redis.createClient();
userCreate.subscribe("userCreate", "userCreate");

var userDestroy = redis.createClient();
userDestroy.subscribe("userDestroy", "userDestroy");

userCreate.on("message", function(channel, data) {
   socket.to(JSON.parse(data).username).emit('beginSession', data);
});

userDestroy.on("message", function(channel, data) {
   socket.to(JSON.parse(data).username).emit('endSession', data);
   socket.leave(JSON.parse(data).username);
});

But when ever i try to emit message from server to client i broadcast message to everyone. What am I doing wrong?

Well, from the syntax point of view you are doing everything correct.

Didn't you forget to specify the userId property in the endSession ?

userDestroy.on("message", function(channel, data) {
   socket.to(JSON.parse(data).userId).emit('endSession', data);
   socket.leave(JSON.parse(data).userId);
});

If that doesn't work - you should provide the contents of a data object

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