The following code works just fine, when I do pub/sub using socket.io.
Basically, I send a chat message from browser. At the server, I listen to this message and emit it back to all, the same message from the server. So, I expect 1 message to be returned/printed for every message I send.
With the below, I can login from multiple browsers, and when I send a chat message, it gets returned/printed as a single chat message as expected.
io.use(socketHandshake({store: sessionStore, key:'jsessionid', secret:'secret', parser:cookieParser()}));
io.on('connection', function (socket) {
socket.on('chat', function (message) {
io.emit('chat', "hello world");
});
});
However, when I try to do pub/sub using redis, there is a problem.
From first browser: 1 chat message results in printing out 1 chat message
From second browser: 1 chat message results in printing out 2 chat messages
From third browser: 1 chat message results in printing out 3 chat message
var sub = redis.createClient();
var pub = redis.createClient();
sub.subscribe('chat');
io.use(socketHandshake({store: sessionStore, key:'jsessionid', secret:'secret', parser:cookieParser()}));
io.on('connection', function (socket) {
socket.on('chat', function (message) {
// io.emit('chat', "hello world");
pub.publish('chat', "hello world");
});
sub.on('message', function (channel, message) {
io.emit(channel, message);
});
});
What am I missing ? I'm a beginner and I'm trying out this example http://blog.cloudfoundry.org/2013/01/24/scaling-real-time-apps-on-cloud-foundry-using-node-js-and-redis/ using latest versions of express, socket.io, socket.io-handshake and redis.
I'm getting stumped at this redis pub/sub. Please help.
You're adding a new 'message' handler for every connection. So that is why you start seeing more and more duplicates with more and more connections. Try moving your sub.on('message', ...);
outside of your socket.io connection handler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With