1

I am trying to implement a functionality wherein when a user is viewing a page, he should be automatically subscribed a Redis channel unique to that user. And all message published to that Redis channel should be received by the client side.

Below is by client side code,

var socket = io.connect('localhost:5000');

socket.on('connect', function(){
  socket.emit("subscribe",$("#app_id").text());
});

socket.on('message', function(message) {
  $("#lst").append("<li>" + message + "</li>")
});

And on the nodejs server, I have below code,

var client = redis.createClient();

io.sockets.on('connection', function (socket) {

  socket.on("subscribe",function(channel){
    client.subscribe(channel);
    socket.join(channel);
  });

  client.on("message", function(channel, message){
    socket.broadcast.to(channel).emit('message', message);
  });
});

When I open the client page in two separate browsers, its subscribing to the two channels correctly and message published to those Redis channels are shown at client side. But if I refresh the page, the number of messages which I get is double and if I refresh again, it adds up. I guess the listeners getting added-up on each refresh.

I have coded the Redis listener inside the socket.io connection listener because I want to emit the message to the socket.This may be cause of the problem am facing. Dono how else to do it as I need socket instance to send message to client side. Please help on this.

Sathish Jayaram
  • 129
  • 3
  • 14

1 Answers1

1

as you already told: remove the listener on disconnect.

Have a look at how-to-remove-redis-on-message-listeners and socket-io-handling-disconnect-event for further reading.

untested sample

var client = redis.createClient();

io.sockets.on('connection', function (socket) {

  var broadcast = function(channel, message){
    socket.broadcast.to(channel).emit('message', message);
  }

  socket.on("subscribe",function(channel){
    client.subscribe(channel);
    socket.join(channel);
  });

  socket.on('disconnect', function() {
    client.unsubscribe(channel);
    client.removeListener(broadcast)
  })

  client.on("message", broadcast);
});
Community
  • 1
  • 1
dahrens
  • 3,879
  • 1
  • 20
  • 38