Simple Chat Application Using Redis, Socket.io, and Node.js

Install Redis on Ubuntu

Once the program has been installed, Redis comes with a built in script that sets up Redis to run as a background daemon. To access the script move into the utils directory:

  • cd utils
  • sudo ./install_server.sh

As the script runs, you can choose the default options by pressing enter. Once the script completes, the redis-server will be running in the background. You can start and stop redis with these commands (the number depends on the port you set during the installation. 6379 is the default port setting):

  • sudo service redis_6379 start
  • sudo service redis_6379 stop

You can then access the redis database by typing the following command:

  • redis-cli

You now have Redis installed and running. The prompt will look like this:

  • redis 127.0.0.1:6379

To set Redis to automatically start at boot, run:

  • sudo update-rc.d redis_6379 defaults

To check detail information for your installation:

  • redis-cli
  • info

Make sure you have the latest version installed!

Creating a simple chat application:
Server Side Code (app.js):

var app = require('http').createServer(handler);
app.listen(8088);
var io = require('socket.io').listen(app);
var redis = require('redis');
var fs = require('fs');

function handler(req,res){
    fs.readFile(__dirname + '/index.html', function(err,data){
        if(err){
            res.writeHead(500);
            return res.end('Error loading index.html');
        }
        res.writeHead(200);
        console.log("Listening on port 8088");
        res.end(data);
    });
}

var store = redis.createClient();
var pub = redis.createClient();
var sub = redis.createClient();

io.sockets.on('connection', function (client) {
    sub.subscribe("chatting");
    sub.on("message", function (channel, message) {
        console.log("message received on server from publish ");
        client.send(message);
    });
    client.on("message", function (msg) {
        console.log(msg);
        if(msg.type == "chat"){
            pub.publish("chatting",msg.message);
        }
        else if(msg.type == "setUsername"){
            pub.publish("chatting","A new user in connected:" + msg.user);
            store.sadd("onlineUsers",msg.user);
        }
    });
    client.on('disconnect', function () {
        sub.quit();
        pub.publish("chatting","User is disconnected :" + client.id);
    });
    
  });

The index.html file:

<html>
<head>
    <title>Socket and Redis in Node.js</title>
    <script src="/socket.io/socket.io.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
</head>
<body>
<div id="username">
    <input type="text" name="usernameTxt" /> <input type="button" name="setUsername" value="Set Username" />
</div>
<div id="sendChat" style="display:none;">
    <input type="text" name="chatTxt" /> <input type="button" name="sendBtn" value="Send" />
</div>
<br />
<div id="content"></div>
<script>    
    $(document).ready(function() {
        var username = "anonymous";
        $('input[name=setUsername]').click(function(){
	        if($('input[name=usernameTxt]').val() != ""){
	            username = $('input[name=usernameTxt]').val();
	            var msg = {type:'setUsername',user:username};
	            socket.json.send(msg);
	        }
            $('#username').slideUp("slow",function(){
                $('#sendChat').slideDown("slow");
            });
        });
        var socket = new io.connect('http://localhost');
        var content = $('#content');

        socket.on('connect', function() {
            console.log("Connected");
        });

        socket.on('message', function(message){
            content.append(message + '<br />');
        }) ;

        socket.on('disconnect', function() {
            console.log('disconnected');
            content.html("<b>Disconnected!</b>");
        });

        $("input[name=sendBtn]").click(function(){
            var msg = {type:'chat',message:username + " : " +  $("input[name=chatTxt]").val()}
            socket.json.send(msg);
            $("input[name=chatTxt]").val("");
        });
    });
</script>
</body>
</html>

To run this application, you must install node sever, redis, and socket.io.
After that, simply run: node app.js
Then open your browser and navigate http://localhost:8088

Advertisements
This entry was posted in open-source. Bookmark the permalink.

One Response to Simple Chat Application Using Redis, Socket.io, and Node.js

  1. banckle says:

    Thanks for providing wonderful information I would suggest you to check Banckle Chat ( http://banckle.com/apps/chat/overview.html ) which is one of the best live chat application for your website having lots of built-in featuers.

    Signup FREE: https://apps.banckle.com/action/signup

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