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
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:
In my opinion, the publish is done before the subscribe function has finished.
You could use something like this
This will only execute the publish once the subscribe has been done.