Hi, new to socket.io here. I find it very easy to build simple chat app following tutorial, but having difficulties as I progress to build more complex features.
I want to create a group chat app like whatsapp or facebook messenger. I can do this with room feature and broadcasting messages to the room when all users are connected and joined to the same room. Where I'm stuck is when I start a new group chat.
Suppose, A wants to create a new group chat with B and C. So A starts with a message like this. (assume B, C are also connected to socket.io server)
{
id: 'groupchat-123', // randomly generated id
receipients: ['B', 'C'],
message: 'Hey',
sender: 'A'
}
The outcome I want is, B & C receives this message on the client with no user interaction.
On server side, A will do socket.join('groupchat-123'). But B, and C haven't join to the same room yet, hence broadcasting won't do anything to B and C. How do I make B and C join the room before broadcasting? How'd I achieve this if I have multiple node instances?
I think I figured it out for single instance.
Basically I'm using a users hash to store socket ids like this
users = {
A: "A's socket id',
B: "B's socket id',
C: "C's socket id'
}
then use this to get socket then finally join to a room
var soc = io.sockets.connected[socketid];
soc.join('groupchat-123');
Still not sure how to achieve this when using multiple node instances.
I would check socket.io-redis, but I'm not sure If that will work without the following pull request:
https://github.com/Automattic/socket.io-redis/pull/15
Basicly you need something to communicate between the different instances. You could write your own redis pub/sub system. I wrote redis-pubsubber to make that slightly easier.
Hi @peteruithoven, thanks for suggestion.
I think you're right on. Communication between different instances seems like exactly what I need.
I am actually using socket.io-redis. As I monitor redis server, I see messages broadcasted to a room are being published. I'm having hard time writing a handler for those published messages. (Also new to redis)
I peeked at socket.io-redis code and subscribe method is inside Redis.prototype.add function. Should I explicitly call this add function?
The trick to socket.io-redis is that it makes sure broadcasted messages arrive to all clients connected to all instances. You can't listen to them on the server, unless you create clients on the server.
Got it. So I've made it work by creating predefined channel("join") from server and let subClient to subscribe to that channel. Then I'm publishing to that channel("join") when I need to force other sockets to join a specific room. Thanks for your help!
I dont suppose you have some code to share?
+1 to code to share :)
+1
Most helpful comment
I dont suppose you have some code to share?