2

I was inspired by this: http://socket.io/docs/using-multiple-nodes/#passing-events-between-nodes, and right now I want to synchronize my two socket.io instances through the redis adpter.

This 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 I connecting to server1.js (port 3000) - I see 'connection. test = 1', it's good, but the console of the second server is still clean. I want second server (port 4000) to do the same (print 'connection = 1').

What I'm doing wrong? Can you show me an example how to use the adapter?

Thanks

moskrc
  • 1,220
  • 1
  • 12
  • 23

1 Answers1

5

If you only connect to server1:3000 there's no way the io.on('connection', ...) would be triggered on server2:4000 - after all, you are not connected to that server.

Each client will connect to only one of your servers. If you were not using the Redis adapter clients connected to different servers would be unable to communicate. Now with the Redis adapter the servers know about the clients of each other and can broadcast messages to all connected clients of all servers.

vesse
  • 4,871
  • 26
  • 35
  • That sounds right. Two things to try. Try attaching data to a socket. ex socket.username = 'ted'. If that doesn't work you can always install redis pub/sub and create an adapter like communication channel for the nodes, so you can share non socket.io messages. – Eddie Jul 17 '15 at 19:39
  • I am having same two servers and I am using socket.io@1.4.5 in bot server and client.In my code add a time to print total number of sockets connected. I am getting correct number in one server but in another i am getting only 0. The below is what I am using for count check. Object.keys(io.sockets.connected).length) – Soorya Prakash Aug 02 '16 at 07:04