I am building a web application with Node (Express) and Socket.IO having chat features. Since opening a new tab on the page establishes a new socket connection, I need to group all instances of the same user into my room based on the Express session ID so that all messages directed to the mentioned user are displayed on all duplicated tabs. This is in addition to any other room / channel to which they may have already entered the system. At a minimum, users subscribe to two chats: the actual "real" room and their own channel using the session ID.
The problem is that all sockets for my sessionID are also in a more common room (and should be for receiving messages from other users). When I send a general chat message, I would like to omit any sockets corresponding to the sending user, since they already received the message through their own channel. I went ahead and made a hash of arrays containing lists of socketIDs for this session, with the key on sessionID. I saw several different syntaxes for specifying exception lists, but no one works for me.
Corresponding code with some parts omitted for brevity:
var sessionSockets = {};
io.sockets.on('connection', function(socket){
if(!io.sockets.manager.rooms["/" + sessionID]) {
sessionSockets[sessionID] = [];
//send message indicating log on to all sockets except for my session
}
socket.join(sessionID); //create private channel for all sockets of the same sessionID
sessionSockets[sessionID].push(socket.id);
socket.on('chat', function(data){
var payload = {
message: data.msg,
from: data.user
};
//send back as personal message to all sockets for this session
io.sockets.in(sessionID).emit('me',payload);
//send to everyone else as regular message; WHAT SYNTAX?
io.sockets.in('').except(sessionSockets[sessionID]).emit('chat', payload);
}
}
tl; dr: How can I send a message to a subset of users in a channel / room without manually comparing arrays?
source
share