M
M
moskrc2014-10-22 22:14:31
Redis
moskrc, 2014-10-22 22:14:31

How to scale a chat written in socket.io/nodejs?

Hello!
I wrote some kind of chat on socket.io and I want to scale it to two servers.
I read this this: socket.io/docs/using-multiple-nodes/#passing-event... set up nginx and now the client gets to one of these servers.
The problem is that I use a variable in each socket.io instance to store a list of the people in the room and the names of those rooms.
If one person connected to one instance, and the other to another, then they do not see each other.
From the above article I read about redis adpter. I thought that I would add these lines and my two instances would be synchronized via redis. But that did not happen.
Here is my code:

//FIRST SERVER (server1.js)

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

var test = 0;

io.on('connection', function (socket) {
    test+=1;
    console.log("connection. test = " + test);
});

//SECOND SERVER (server2.js)


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

var test = 0;

io.on('connection', function (socket) {
    test+=1;
    console.log("connection. test = " + test);
});

When the client connects to server1.js (port 3000) - I see 'connection. test = 1', that's good, but the console in which the second instance is running remains empty. I want the second instance to do the same (print 'connection = 1').
What am I doing wrong? Maybe someone knows where you can see an example of using socket.io-redis
Thanks

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Kaloshin, 2014-10-28
@moskrc

io.on('connection', function (socket) {
//
});

This event will fire when a persistent connection between the client and server is successfully established.
Since a socket connection is a single connection, it will either hit the 1st instance or the 2nd instance. And this event will fire either here or there.
If for some reason you need to see the connection event in the console in both instances,
I would try the following:
1. Use the native redis module as a channel between instances.
2. If the connection was successful, I would send a notification to the redis.publish channel about a new connection
BUT! It is necessary to manually define the events that need to be calculated on the second instance, otherwise there is no sense in such scaling, because both instances will process the same commands.
In summary: It makes no sense. If there is a need, you just need to notify the second service through the radish.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question