user2565968
user2565968

Reputation:

Listening channels redis in node.js

There is such a simple code wiretapping channels radishes.

redisClient = redis.createClient();
redisDummyPublishClient = redis.createClient();
//redisClient.auth("25c9721b4e579fc5af961f944e23f46f");


//look for connection errors and log
redisClient.on("error", function (err) {
    console.log("error event - " + redisClient.host + ":" + redisClient.port + " - " + err);
});


var channels_active = [];
io.sockets.on('connection', function (socket) {
    redisClient.on('ready', function() {
    redisClient.psubscribe('*');
  });


  function CreateSocketsAccept (eventNameListen, channel, message){
    var obj = { channel : channel, message : message}
      for (i in eventNameListen) {
          io.sockets.in(channel).emit(eventNameListen[i], obj);
       } 
    }

  redisClient.on('pmessage', function(pattern, channel, message) {
    console.log(channel);
    CreateSocketsAccept(channels_active, channel, message);
  });     

});

setInterval(function() {
  var no = Math.floor(Math.random() * 100);
  redisDummyPublishClient.publish('478669c7fa549970e36eac591cdca62e', 'Generated random no ' + no);
}, 5000);

Send data from PHP:

$this->load->library( 'rediska_connector' );
// Other way to publish
$rediska = new Rediska();
$rediska->publish('realtime', 'PHP SENDING');

The question is, why does not output to the console the names of available channels?

Upvotes: 0

Views: 1703

Answers (1)

robertklep
robertklep

Reputation: 203329

As far as I'm aware, you can't listen on all channels...

If you want to subscribe to a pattern, you need to use psubscribe:

redisClient.psubscribe('*');

And instead of listening for message events, listen for pmessage events:

redisClient.on('pmessage', function(pattern, channel, message) {
  console.log(channel);
});

(thanks @DidierSpezia for correcting me :)

EDIT: you can't mix socket.io and the Redis client like that, you need to move the Redis code outside the socket.io handler:

// No need for this because it's doing nothing:
// io.sockets.on('connection', function(socket) { ... });

redisClient.on('ready', function() {
  redisClient.psubscribe('*');
});

function CreateSocketsAccept (eventNameListen, channel, message){
  var obj = { channel : channel, message : message}
  for (i in eventNameListen) {
    io.sockets.in(channel).emit(eventNameListen[i], obj);
  }
}

redisClient.on('pmessage', function(pattern, channel, message) {
  console.log(channel);
  CreateSocketsAccept(channels_active, channel, message);
});

Upvotes: 2

Related Questions