Reputation: 5513
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.
Upvotes: 4
Views: 4499
Reputation: 1
i know its an old question, but maybe this can help give another solution for people out there, i found myself a solution after had this error yesterday. try to change io.emit(channel, message); into socket.emit(channel, message);
Upvotes: 0
Reputation: 106706
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.
Upvotes: 10