Mar 25, 2013

How To Make A Chat Program In Node JS

Today we will start with NodeJS.


NodeJS

So what is NodeJS?


In simple terms, JavaScript on server side. NodeJS uses Googles V8 engine. Its basically a javascript library which is executed on server side. Its also known as JavaScript without browser.


When and why to use nodejs?


Choosing a technology depends on the developer who is going to take it ahead. NodeJS is very simple, you just need to know javascript. NodeJS can be used for online gaming, chat programming, CRM management and also for blogging. There are several plugins available which make your job easy.



So today lets start with a simple chat program.



Installing NodeJS on Windows




First download the latest copy of nodejs from here. After installation open cmd and just type node -v. This will output you the current installed version of nodejs.




Now create a folder on desktop, name it as node-chat, using cmd navigate to that directory. Now inside that folder create a file package.json. This file contains all the dependencies and other plugin information. Paste below code inside it:



[js]
{
"name": "node_chat",
"version": "1.0.0-4",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node app.js"
},
"dependencies": {
"socket.io": "0.9.11",
"connect": "2.7.1"
},
"author": "Niraj Chauhan",
"license": "BSD",
"subdomain": "node-chat",
"engines": {
"node": "0.6"
}
}
[/js]

Above json is simple, it takes few parameters like name of author, filename which is going to be executed first, dependencies etc.



Now in cmd just type npm install. This will install all required dependencies which are mentioned inside the json file.



After above command if you check the folder, it consists with a new folder named as node_modules This ensures that all the important modules are installed.



Create a file app.js and paste the below code in it.


[js]
var io = require('socket.io'),
connect = require('connect'),
url = require('url'),
sys = require('sys'),
http = require('http'),
fs = require('fs');

var port = 3000;


var app = connect().use(connect.static('public')).listen(port);
var chat_room = io.listen(app);
console.log('Listening to port ' + port);

chat_room.sockets.on('connection', function (socket) {
socket.emit('entrance', {
message: 'Welcome to the chat room!'
});

socket.on('disconnect', function () {
chat_room.sockets.emit('exit', {
message: 'A chatter has disconnected.'
});
});

socket.on('chat', function (data) {
message = {
user: data.message.user,
message: data.message.message
};
chat_room.sockets.emit('chat', {
message: message
});
});

chat_room.sockets.emit('entrance', {
message: 'A new chatter is online.'
});
});
[/js]

If you have worked with server side technology like php, java etc then you ll understand the basic from above. Firstly we have included some modules which we will need. We will be using socket.io to make a flawless connection between server and client. We will also be using connect


Connect offers a createServer method, which returns an object that inherits an extended version of http.Server. Connect's extensions are mainly there to make it easy to plug in middleware. That's why Connect describes itself as a "middleware framework," and is often analogized to Ruby's Rack.

After including required files we listen to a port which redirects to a folder public and finally we open the socket after successful connection between server and client.


Using opened socket variable, we define different methods inside the connection function.




  • entrance: Used when a socket connection established between server and client

  • disconnect: Used when a client breaks the connection

  • chat: Used to transfer messages between different clients via server.



So now lets create a foder and name it to public. This folder will contain all the UI html and css files. Here I ll be using twitter bootstrap.



So by now your folder structure should be something like this:




node-chat/
|--node_modules/
|--public/
|----css/
|----img/
|----js/
|----index.html
|--app.js
|--package.json



Inside your index.html file paste the below code


[js]
<script src="js/jquery-1.7.2.min.js"></script>
<script src="http://localhost:3000/socket.io/socket.io.js"></script>
<script type="text/javascript" charset="utf-8">
var socket = io.connect('ws://localhost:3000/');
var user = {
name: ''
}
jQuery(document).ready(function() {

jQuery('#chat_box').keypress(function(event) {
if (event.which == 13) {
socket.emit('chat', {
message: {
user: user.name,
message: jQuery('#chat_box').val()
}
});
jQuery('#chat_box').val('');
}
});

});

function startChat() {
user.name = $('#username').val();

var log_chat_message = function(message, type) {

if (type == 'chat') {
var li = jQuery('<li />').html('<span>' + message.user + '</span>: ' + message.message);
} else {
var li = jQuery('<li />').html('<span>' + message + '</span>');
}


jQuery('#chat_log').append(li);
};

if (user.name != '') {
$('#loginDiv').fadeOut();
$('#chat').fadeIn();

socket.on('chat', function(data) {
log_chat_message(data.message, 'chat');
});

socket.on('entrance', function(data) {
log_chat_message(data.message, 'system');
});

socket.on('exit', function(data) {
log_chat_message(data.message, 'system');
});

} else {
alert('Please enter your username');
}
}
</script>
[/js]


Above code is simple jquery, which contains some functions for chatting, login, printing message etc. So quickly I ll explain you the important part of chat.




When user opens the page, we call the socket file, this file is installed inside modules using the json file. Then first we open a socket connection between server and user. This triggers the app.js file and entire connection is established. Then by using the functions of connection which is declared inside app.js file(chat, entrance, exit) we call those functions from here. Each function passes and takes some message. Using chat we take message from user who typed, passed it to server, server takes that message and throws to all user within the socket connection.



To execute this chat, just run this command in cmd within the directory where app.js file exists node app.js, then in browser navigate to http://localhost:3000/


You can check the working demo and download the files. I have just covered the important flow of the code and how nodejs and sockets can be helpful. This chat works in almost all browsers and devices, this is the plus point of using sockets via nodejs