3

I am developing a real time application using Node.js, Socket,io, Redis. I try to send a private message to one client from worker, but it does not work. Array io.sockets.connected on worker is empty and i can't refer to the client.

Code on master:

var io = require('socket.io')(30042); //socket.io(<port>) will create a http server
var redis = require('socket.io-redis');
io.adapter(redis({ host: 'localhost', port: 6379 }));
io.on('connection', function (socket) {
    io.sockets.connected[socket.id].adapter.remoteJoin(socket.id, 'new_room', function  (err) {});
});

Code on worker:

var SocketIO = require('socket.io');
var redis = require('socket.io-redis');
io = new SocketIO(); //start redis socket-io
io.adapter(redis({host: 'localhost', port: 6379})); // where your redis server is located

//send to all users in room - works perfectly
io.to('new_room').emit('chat message', 'Test global msg from worker');

//????
//dont work - io.sockets.connected is empty
io.sockets.connected['socket_id_from_master'].emit('chat message', 'Test private msg from worker');

What am I doing wrong?

  • 1
    I found a way out: Each Socket in Socket.IO is identified by a random, unguessable, unique identifier Socket#id. For your convenience, each socket automatically joins a room identified by this id. Worker code: io.to(id).emit('chat message', 'Test private msg from worker'); – Michael Kors Feb 16 '17 at 21:22

1 Answers1

0

Since your worker doesn't know anything about the connected sockets, you need to get them from the adapter, which in this case is Redis.

To get connected sockets you need to call: io.sockets.adapter.clients