RedGiant
RedGiant

Reputation: 4750

redis sub/pub in or out of io.connect callback

Should I put the redis subscription event out of the io.connect callback if I want to send the data to everyone who is connected? Or is it better to put it inside the io.connect like this:

    io.on('connection', function(socket){ 
      sub.on('message',function(channel,msg){
       Project.findAll({ where: {id: msg} },{raw:true}).success(function(d) {
       console.log(d);
       io.sockets.emit("activities",d);
      })
     });
    });

Would there be any difference?

Node.js

var express = require('express'),
    app = express(),
    http = require('http').createServer(app),
    io = require("socket.io").listen(http),
    redis = require("redis"),
    Sequelize = require('sequelize');

    var pub = redis.createClient();
    var sub = redis.createClient();
    sub.subscribe('global');

    app.get('/p/:tagId', function(req, res){ 
       res.render('index.html')
    });

    sub.on('message',function(channel,msg){
      Project.findAll({ where: {id: msg} },{raw:true}).success(function(d) {
      console.log(d);
      io.emit("activities",d);
     })
    });

    io.on('connection', function(socket){ 

     //** code **//
    })

Can anyone show me what's wrong with the node.js's code?

Upvotes: 0

Views: 96

Answers (1)

Barış Uşaklı
Barış Uşaklı

Reputation: 13522

Your second code sample looks correct. You don't want to put the sub.on('message', function(channel, msg) { inside the socket.io connection handler. That would add a new event handler every time someone connects.

Did you test if it is working? You need to publish something onto the channel global for the message callback to be triggered.

pub.publish('global', 'here is a message');

Upvotes: 1

Related Questions