Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Redis pub/sub for chat server in node.js

Redis pub/sub for chat server in node.js

Problem

I'm trying to work the Redis Cookbook example:

var http = require('http'),
io = require('socket.io')
fs = require('fs'),
redis = require('redis'),
rc = redis.createClient(9189, "pike.redistogo.com");
rc.auth("passwd", function() {
    console.log("Connected! to redistogo!");});

rc.on("connect", function() {
    rc.subscribe("chat");
    console.log("rc connect event");
});

I am successful through here but never get "message."

rc.on("message", function (channel, message) {
 console.log("Sending: " + message);
 socketio.sockets.emit('message', message);
});

webpage = http.createServer(function(req, res){
console.log('webpage request starting...');

fs.readFile('./index.htm', function(error, content) {
    if (error) {
        res.writeHead(500);
        res.end();
    }
    else {
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.end(content, 'utf-8');
     }
 });
 });

 webpage.listen(7777);

my client side index.htm is this




    Chat with Redis

    how does a client publish to a specific Redis "chat" channel.

    Problem courtesy of: Charles Short

    Solution

    If you are using redis pub/sub functionality within your node.js program you should dedicate one redis client connection for listening on some channel and second redis client connection for sending normal commands and/or publishing messages to your channel(s). From node_redis docs:

    When a client issues a SUBSCRIBE or PSUBSCRIBE, that connection is put into "pub/sub" mode. At that point, only commands that modify the subscription set are valid. When the subscription set is empty, the connection is put back into regular mode.

    If you need to send regular commands to Redis while in pub/sub mode, just open another connection.

    Your problem is also related to these questions:

    • Redis / Node.js - 2 clients (1 pub/sub) causing issues with writes
    • Why can't I have a single Redis client acting as PUB and Sub in the same connection?
    Solution courtesy of: yojimbo87

    Discussion

    View additional discussion.



    This post first appeared on Node.js Recipes, please read the originial post: here

    Share the post

    Redis pub/sub for chat server in node.js

    ×

    Subscribe to Node.js Recipes

    Get updates delivered right to your inbox!

    Thank you for your subscription

    ×