August 18, 2015 7:10 pm

How to Create Real-time Chat Application with Node.js Part 3

The back-end of the chat First we load the express module and set the port to be equal to process.env.PORT (which will be an environment variable defined by Heroku) or 8080 if we are on localhost. Then we create our Express server which will respond to HTTP requests. We load the html entities module, set Socket.IO to listen to our server and require Redis. Theredis.createClient takes as its first argument the port the database is on and as a second argument – the host it is on.

Create Real-time Chat Application with Node

[wpdm_file id=147]DEMO

We provide the values given to us by Redis Labs and useclient.auth(‘password’, callback)to authenticate ourselves to the database with the password given to us by Redis Labs.

varexpress = require("express");
varport = process.env.PORT || 8080;
varapp = express();
varserver = app.listen(port, function() {
console.log("Server running");
})

varEntities = require("html-entities").XmlEntities,
entities = new Entities();
vario= require('socket.io').listen(server);
varredis= require("redis"),
client = redis.createClient(15288,'pub-redis-16297.us-east-1-3.6.ex5.redislabs.com',{no_ready_check: true});
client.auth('mySecretPassword', function (err) {
if (err) throw err;
});

Then, we set up the folder for static files to be called public with: app.use(express.static(“public”));

app.use(express.static("public"));

Afterwards, we insert our application logic nested within the callbacks that tell usthat we have a connection with Redis and that Socket.IO has connected the client:

client.on('connect', function() {

	console.log('connected');
	io.on('connection', function (socket) {
    //logic here
	});
});

When a user joins, we add the entity encoded nickname to the database and set the name to that socket. Finally, we get all nicknames by telling Redis to give us values from index 0 to index -1 with:

client.lrange('nicknames', 0, -1, function (err, NICKNAMES) {
// do something with the data
});

After we get all the nicknames, we emit them to the client from the server with io.sockets.emit(‘eventName’, valueToPass);

All this happens only if the user’s name consists of less than 25 characters.

socket.on("join", function (data) {
if (data.length<= 25) {
client.lpush("nicknames", entities.encode(data));
socket.nickname=  entities.encode(data);
client.lrange('nicknames', 0, -1, function (err, result) {
io.sockets.emit('online', result);
        });
    }

We also get all messages when the user joins using the same lrange method and emit multiple events for each message stored there using a loop (in the callback):

client.lrange('messages', 0, -1, function (err, messages) {
for (vari= messages.length- 1; i>= 0; i--) {
socket.emit('incomingMessage', messages[i]);
        }
    })
})

Near the end, when the client sends to the server a message event we check if the message contains less than 100 characters and if the nickname has 25 characters or less and if so we add the message to Redis using lpush(‘key’, ‘value’).

If the criteria mentioned above are met, we also trim the messages key in the database to contain at most the last 21 messages using the ltrim(‘key’,startingIndex,endingIndex) method and we send the newly created message to all connected clients by broadcasting the event with io.sockets.emit(‘eventName’, valueToPass).

socket.on("message", function (data) {
if (data.length<100 &&socket.nickname&&socket.nickname.length<= 25) {
varmessage = socket.nickname+ ": " + entities.encode(data)   ;
client.lpush("messages", message);
client.ltrim("messages", 0, 20);
io.sockets.emit("incomingMessage", message);
    }

    });

Part 1: How to Create Real-time Chat Application with Node.js Part 1

Part 2: How to Create Real-time Chat Application with Node.js Part 2

Part 4: How to Create Real-time Chat Application with Node.js Part 4

Author Ivan Dimov

Ivan is a student of IT, a freelance web designer/developer and a tech writer. He deals with both front-end and back-end stuff. Whenever he is not in front of an Internet-enabled device he is probably reading a book or traveling. You can find more about him at: http://www.dimoff.biz. facebook, twitter


Tutorial Categories:

5 responses to “How to Create Real-time Chat Application with Node.js Part 3”

  1. Vikrant says:

    Demo is not working 🙁
    there is some error.
    please check photo and Like below

    “An error occurred in the application and your page could not be served. Please try again in a few moments.
    If you are the application owner, check your logs for details. “

  2. Hoxxy says:

    Messages not showing up in Safari 5.1.7 however messages from Safari can bee seen in others so they are being sent.

Leave a Reply

Your email address will not be published. Required fields are marked *