How socket.io sends messages to multiple servers?

The Socket.io API has the ability to send messages to all clients.

With one server and all sockets in memory, I understand how this server can send a message to all its clients, which is pretty obvious. But what about multiple servers using Redis to store sockets?

If I have client a connected to server y and client b connected to server z (and Redis for the store) and I do socket.broadcast.emit on one server, the client on the other server will receive this message. How?

How do clients that are actually connected to another server receive this message?

  • Does one server tell another server to send a message to a connected client?
  • Is the server establishing its own connection with the client to send this message?
+6
source share
2 answers

Socket.io uses MemoryStore by default, so all connected clients will be stored in memory, which makes it impossible (well, not quieter, but in more detail) to send and receive events from clients connected to another socket.io server.

One way to make all Socket.io servers receive all events is that all servers use REDIS Pub-Sub. So, instead of using socket.emit, you can publish redis.

 redis_client = require('redis').createClient(); redis_client.publish('channelName', data); 

And all socket servers subscribe to this channel through Redis and, after receiving the message, emit its clients connected to them.

 redis_sub = require('redis').createClient(); redis_sub.subscribe('channelName', 'moreChannels'); redis_sub.on("message", function (channel, message) { socket.emit(channel, message); }); 

Difficult thing !! But wait, it turns out you do not need such code to achieve the goal. Socket.io has a RedisStore that essentially does what the code above should do so that you can write Socket.io code as you would for one server, and will still propagate to another socket.io server via Redis.

To summarize, socket.io sends messages to multiple servers using Redis as a channel instead of memory.

+7
source

There are several ways to do this. More details on this . A good explanation of how pub / sub works in Redis is here in the Redis docs . An explanation of how the paradigm in general works is here on Wikipedia .

Specifying Redis Docs:

SUBSCRIBE, UNSUBSCRIBE and PUBLISH implement the publication / subscription of the messaging paradigm, where (with reference to Wikipedia) senders (publishers) are not programmed to send their messages to specific receivers (subscribers). Rather, published messages are characterized by channels, without knowing what (if any) subscribers can be. Subscribers express interest in one or more channels and receive only messages of interest, without knowing that (if any) publishers exist. This disabling of publishers and subscribers can provide greater scalability and a more dynamic network topology.

+1
source

Source: https://habr.com/ru/post/948567/


All Articles