1

I'm building an app where the server occasionally publishes data on a given channel:

redisClient.publish('global-channel', data);

Clients need to be able to connect to the server and listen to the global broadcast. Is there anything wrong with this approach? Specifically, the creation of a redisClient for each socket connection?

io.sockets.on('connection', function(socket){
  var socketRedis = redis.createClient();
  socketRedis.subscribe('global-channel');

  socketRedis.on('message', function(ch, msg){
    socket.emit('event', msg);
  });
});

I'm new to Node, Redis, AND socket.io ... still learning which piece should handle certain tasks and where (server vs. client side) -- thanks!

Dan
  • 4,197
  • 6
  • 34
  • 52

1 Answers1

2

Yes, there is a better way:

var socketRedis = redis.createClient();
// Subscribe to the channel only one time
socketRedis.subscribe('global-channel');

// Accept any connection you want from socket.io
io.sockets.on('connection', function(socket){
  // Do what you want here
});

// Add only one listener to the channel and broadcast
// the message to everyone connect on socket.io
socketRedis.on('message', function(ch, msg){
  io.sockets.emit('event', msg);
});
FGRibreau
  • 7,021
  • 2
  • 39
  • 48
  • Thank you -- (I'm NOT asking this rhetorically, b/c I honestly don't know) -- but doesn't this go to the whole debate as to whether it's better to rely on socket.io or Redis for mass-comms to clients? for instance, Redis allowing greater scalability b/c it doesn't rely directly on the client-webserver connection? – Dan Dec 10 '13 at 13:15
  • Found another question related to this (Redis vs. Socket.io): http://stackoverflow.com/questions/10167206/redis-pub-sub-or-socket-ios-broadcast ... see the first answer – Dan Dec 10 '13 at 13:39
  • Yes the first answer implementation would be something like to the code I gave you. Each socket.io processes would handle a group of users and would forward each message published from Redis to each of them. – FGRibreau Dec 10 '13 at 14:37