Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How io.adapter works under the hood?

I'm working on 1-1 chat rooms application powered by node.js + express + socket.io. I am following the article: Socket.IO - Rooms and Namespaces

In the article they demonstrate how to initiate the io.adapter using the module socket.io-redis:

var io = require('socket.io')(3000);
var redis = require('socket.io-redis');
io.adapter(redis({ host: 'localhost', port: 6379 }));

Two questions:

  1. In the docs, They are mentioning two more arguments: pubClient and subClient. Should I supply them? What's the difference?
  2. How the io.adapter behaves? For example, if user A is connected to server A and user B is server B, and they want to "talk" with each other. What's going under the hood?

Thanks.

like image 607
Aharon Avatar asked Sep 24 '14 10:09

Aharon


1 Answers

  1. You do not need to pass your own pubClient/subClient. If you pass host/port, they will be created for you. But, if you want to create them yourself, for any reason (e.g. you want to tweak reconnection timeouts), you create those 2 clients and pass it to adapter.

  2. The adapter broadcasts all emits internally. So, it gives you the cluster feature. E.g. lets suppose that you have chat application, and you have 3 node.js servers behind load balancer (so they share single URL). Lets also assume that 6 different browsers connect to load balancer URL and they are routed to 3 separate node.js processes, 2 users per node.js server. If client #1 sends a message, node.js #1 will do something like io.to('chatroom').emit('msg from user #1'). Without adapter, both server #1 users will receive the emit, but not the remaining 4 users. If you use adapter, however, remaining node.js #2 and node.js #3 will receive info that emit was done and will issue identical emit to their clients - and all 6 users will receive initial message.

like image 88
Nopik Avatar answered Nov 09 '22 18:11

Nopik