Reputation: 250
I'm wondering how to dynamically create chat rooms with socket.io. I've seen this question: What is the proper way to manage multiple chat rooms with socket.io? , but it's not quite what I'm looking for. I want to open chat rooms with an id that I predetermine, so that I can keep track of different conversations within my db, client, etc. I've figured out how to handle the emitting of new messages to the appropriate client, but I can't figure out how to establish the connection dynamically, or if I have to manage multiple sockets at once for many users across many chat rooms.
Heres the node.js code:
websocket.on('connection', (socket) => {
console.log(socket);
clients[socket.id] = socket;
socket.on('5b17803f134204f7f3e274e0-5b17703f134204f7f3e274e0', (message) => onMessageReceived(message, socket));
socket.on('5b17803f134204f7f3e274e0-5b17703f134204f7f3e274e0-join', (chatInfo) => _sendExistingMessages(chatInfo, socket));
});
As you can see, I wish to replace the '5b...' strings with something dynamic. The client code to make this connection is just one line:
this.socket = SocketIOClient(port);
Is there a way to do this? A follow up question would also be how do I manage all of these different sockets? A set of sockets perhaps? Any help would be appreciated, thanks!
Upvotes: 2
Views: 2740
Reputation: 130
With socket.io you generally only need to do a socket.join()
on the room you want them in, which can be your dynamic room name. From there, you can just emit an event to the room.
io.on('connection', function (socket) {
socket.join('5b17803f134204f7f3e274e0-5b17703f134204f7f3e274e0', function (err) {
if(err) {
throw err
}
io.to('5b17803f134204f7f3e274e0-5b17703f134204f7f3e274e0').emit('joined', {})
})
})
If the above example doesn't work, you may need to setup another event handler on the socket, and then have your client send that event to join the room, from there you can fire a callback with the return data to the client
socket.on('joinRoom', function (data, callback) {
socket.join(data, function (err) {
if(err) {
return callback("error")
}
return callback("joined")
})
})
Upvotes: 1