skip to Main Content

I’m totally newbie to redis and I’m trying to create a publish when a client connect to my app and receive it back later on subscribe, in order to apply this logic on further and more complex methods, but it ain’t work for some reason I can’t spot. This is my current code:

const client = redis.createClient({
  port: 6379,
  host: '127.0.0.1'
});

io.on( 'connection', ( socket ) => {

  var sub = redis.createClient();
  sub.subscribe( 'connection' );

  client.publish( 'connection', {message: "user has been connected from port '" + port} , function () { console.log( "client connected" ) } )

  sub.on( "message", ( channel, message ) => {
    console.log( "message received: " + message )
    console.log( channel )
  } )

All inside "sub.on" is not being executed so I’m doing something wrong or missing something important, any hint would be really apreciated.

2

Answers


  1. Chosen as BEST ANSWER

    Problem was that I was trying to pass as an argument an object. Redis only accept strings on publish so this is the correct and valid way to implement it:

    client.publish( 'connection', "{message: 'user has been connected from port '" + port"}" , function ()...
    

  2. In my opinion, the publish is done before the subscribe function has finished.

    You could use something like this

    const client = redis.createClient({
      port: 6379,
      host: '127.0.0.1'
    });
    
    io.on( 'connection', ( socket ) => {
    
      var sub = redis.createClient();
      sub.subscribe( 'connection' );
    
     sub.on('subscribe', function(channel, count) {
        client.publish( 'connection', {message: "user has been connected from port '" + port} , function () { console.log( "client connected" ) } )
     });
    
      sub.on( "message", ( channel, message ) => {
        console.log( "message received: " + message )
        console.log( channel )
      } )
    

    This will only execute the publish once the subscribe has been done.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search