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

Dec 15, 2012

Website content management system – what is it all about?

CMS or the Content management system, in simple words can be explained as PC
software that helps you to amend, alter, make public and maintain the contents from
the central interface end. Initially CMS was designed with the purpose of simplifying
the complex task of writing codes of various versions and to ease up the development
process more flexible and handy. This type of software helps to manage system that
controls and manages the complete content with the help of a workflow procedure
including a collaborative environment.


CMS


CMS helps to centralize data edit, publish and modify at the single back end interface.
This web CMS technique is best used to be in charge of active set of web materials that
are made available online such as websites, media files and document.


Different types of CMS


We have three major types of Content Management System (CMS) namely, online
processing, offline processing and hybrid systems. These processes are being used
in the implementation procedure to describe the deployment pattern for Web CMS via
presentation templates that provide a structural content pattern for your web page.


Online processing system is all about implementing templates requisite condition.
Usually a web page HTML is being generated during a visitor’s entry or when the
page is being pulled off from web cache. It is known that most of the open source web
content management system has the capability to support add-ons that offers the
required support including blogs, forums, web stores, etc. It’s being referred to as add-
ons, widgets, modules, or extensions with open source of paid license model.


Offline processing system is something that is also termed as static site generators.
Pre-process all the content by implementing the right templates ahead of issuing to
generate your web pages. As pre-processing system does not call for server to make
use of the templates at the right time, they subsist as design-time tools.


Hybrid systems
There are systems where both online and offline techniques are being implemented.
Some systems write their exec codes to move on with dynamic HTML condition where
CMS is not deployed on all servers. While the other types of Hydrid systems are either
offline or online base on the functionality.

Nov 20, 2012

jQuery Form Validation Plugin

If you are developing websites then you will come across Form validation. I too and I was using jQuery Validation plugin. This is an awesome plugin but really buggy in IE7/8 browser with different jQuery versions. Its not stable and the developer of this plugin is not looking after the bugs. I reported several times but no response. So finally I decided to make my own validation plugin.

Before I start further let me tell you that currently this plugin only validates INPUT types with number, email and blank value fields. Its still in beta or under development mode.

GITHUB REPO : https://github.com/nirajmchauhan/jQuery-form-validation





Form-Validation



I ll explain you the usage of this plugin by a simple form example



HTML:



[html]
<section>
<form method="post" class="form-horizontal" id="loginForm" onsubmit="return false;">
<div class="control-group">
<label class="control-label" for="inputEmail">Email</label>
<div class="controls">
<input type="text" id="inputEmail" name="user" placeholder="Email" class="required email">
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Password</label>
<div class="controls">
<input type="password" id="inputPassword" name="password" class="required" placeholder="Password">
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox"> Remember me
</label>
<button id="submit" type="submit" class="btn" onclick="javascript:ajaxThrow('#loginForm','#response');">Sign in</button>



</div>
</div>
<div class="alert alert-info" id="response"></div>
</form>
</section>
[/html]




To make a field mandatory, you need to add a class required.
Currently on input types will be accepted so to make if mandatory, use the following attributes :


















class Output
class="required email" This will check for blank field and whether the value is EMAIL ID
class="required number" This will check for blank field and whether the value is a NUMBER
class="required" This field will check for blank values


So now the final is the jQuery:



JS:


[js]
jQuery(function($) {
$(document).ready(function() {

$('#submit').click(function() {
val = $('#loginForm :input').validateForm();
if (val) {
var qstring = $('#loginForm').serialize();
$('#response').fadeIn().html('Form Validated successfully with following fields<br>' + qstring);
}
});

});
});
[/js]




To validate the form, you ll just need to add a line :
val = $('#loginForm :input').validateForm();

This will return a boolean value. And will also add a class error to the respective input field.

Check this in action here :