Simple chatrooms with Redis

Redis the in-memory key value store, provides very efficient storage of data structures and is amazingly fast. Its pub/sub system can be used to create a simple chat room or message broadcasting system for your server with zero code on the backend to handle the messages. I’ll be using Node.js to build a simple chat room (which obviously can be modified to use a message broadcasting system for your server).

Here we have a channel, and anybody can join the channel as a publisher or subscriber. Publisher pushes messages into the channel, which is then sent to all the subscribers. In our chat client we will be creating 2 connections, one as publisher and other as subscriber because we will need to send and receive messages.

First make sure you have the Redis server installed & running. You can download it for free from redis.io.

Next we will need the Redis client for Node.js. To install it execute:

npm install redis

We will be creating to connections to the server, one to publish the messages and another one to receive the incoming messages. To create a server we have:

var redis = require('redis'),
    client = redis.createClient();

We will just need to handle the events from now on. In case of error, we handle it gracefully by:

client.on('error', function(err) {
    console.log("Error: " + err);
});

When we receive an incoming message, we get a message event:

client.on('message', function(channel, message) {
    // we are printing on screen, you can do whatever you want
    console.log(message);
});

Once the client has subscribed, the subscribe event is raised:

client1.on('subscribe', function(channel, count) {
    // we can publish anything in the channel
    process.stdin.on('data', function(text) {
        client2.publish(channel, text);
    });
});

Just make sure you subscribe the client to the channel.

client.subscribe(channel);

Combining all these and a little bit more, I have written a minimal chat client.

With this we can build a high performance message broadcasting for the servers, with very little code handle the transfer of data in the channels.

Advertisements

2 thoughts on “Simple chatrooms with Redis

  1. An improvement would be to change:
    channel = ‘chatroom’;
    by
    channel = process.env.CHANNEL || “chatroom”;

    And then you will have support for multi-room !

    $ CHANNEL=”chatroom” node app.js
    $ CHANNEL=”chatroom” node app.js
    $ CHANNEL=”chatroom2″ node app.js
    $ CHANNEL=”chatroom2″ node app.js

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s