I’m trying pubsub with redis and socketio in nodejs.
My server-side code is:
var io = require('socket.io').listen(server);
var pub = redis.createClient();
io.sockets.on("connection", function(socket) {
console.log('connecteed');
var sub = redis.createClient();
sub.subscribe("messages");
sub.on("message", function(channel, message) {
console.log('message',message);
socket.emit(channel,message);
});
socket.on("disconnect", function() {
sub.unsubscribe("messages");
sub.quit();
});
});
pub.publish("messages", JSON.stringify({type: "foo", content: "bar"}));
My html page index.html contains the following script:
var host = window.location.host.split(':')[0];
var socket = io.connect('http://' + host);
socket.on('messages',function(msg){
console.log(msg);
})
but in index.html console.log is never executed.
It is elementary, but i don’t find the error in my code. Where is it?
That probably because you don’t have any clients connected when you publish the message (hint io.socket.on connect function is executed after pub.publish). Try to replace
with
This will send the message each second and will give you plenty of time to verify your setup.