Rooms
A room is a pool of connected clients. Clients can join _and _leave rooms. Disconnected clients will leave previously joined rooms automatically. Messages sent to a room will not be emitted directly to its connected clients. Each room uses a RoomProxy which implements how to handle incoming events. Basically the proxy sends the event to a messaging-queue and listens for events on the same queue. If a message appears from the queue the proxy will emit it to all connected clients. Through this pattern it's not the current server-instance which emits the event (which would not scale horizontally) but the message-queue. This pattern lets you scale your app easily.
Another advantage of proxies: They can be replaced very easily. So you can start writing you app with a local-in-memory RoomProxy and if you need to scale your app to multiple instances you can change the proxy-type to an external queue using one.
Let's see it in action:
1. Define a RoomProxy (in-memory)
server.roomProxy('my-room-proxy', new LocalRoomProxy());
2. Use the defined proxy to create a room
server.room('awesome-room', 'my-room-proxy');
3. Use the defined room
server.topic('join-room', ({ room }) => {
room('awesome-room').join(); // will automatically leave the room on disposing the topic
});
server.event('say-awesome-hello', ({ payload, room }) => {
room('awesome-room').emit('hello', payload);
});
client.emit('say-awesome-hello', { msg: 'Hi Dudes!' });
client.event('say-awesome-hello', payload => {
expect(payload)
.to.equal({ msg: 'Hi Dudes!' });
});
4. Scale your app
If your app grows and needs to scale you can simply replace the RoomProxy like:
server.roomProxy('my-room-proxy', new RedisRoomProxy());