Dan
Dan

Reputation: 4309

Pipe Redis publish to a socket? Node.js

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!

Upvotes: 1

Views: 627

Answers (1)

FGRibreau
FGRibreau

Reputation: 7239

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);
});

Upvotes: 2

Related Questions