A Web Design Blog


Monday, June 23, 2014

Node JS is the new hotness for developers out there. Well not completely new. It came out about five years back but still if fairly new. It was mostly noted because of its non blocking procedure. And so it would be much useful for creating a file upload system which does not affect the rest of your code, can be used to create a chat system and much more. So lets get started with our chat system.

Getting Started with Chat System :

There are some pre-requisites that you would need to know for creating this. Take a look below for them :
  • Knowledge on Javascript would help
  • Good Text Editor
  • Node JS on your computer
So well just head to this site and install Node JS.

NOTE : This is just a test application to get you started and has no measures for security.

Starting with your Code :

 Create a folder on your desktop and lets call it "chat". Open your terminal or your command prompt and change the directory to the chat folder on your desktop and run the following command.

npm init

It would prompt you to enter you some details regarding your application. Enter those details and hit return. Now that a package.json file would be created in your chat folder. This package.json file would be containing details that you entered in the terminal. And now you need to enter the name of the modules that you need to use in your application. In our case we would be using two modules connect and socket.io. I would be explaining the need of these modules later. For now open up the package.json file that was just created and type in the following in it. You need to enter this before the closing curly braces.
,"dependencies": {
  "connect": "2.0.0",
    "socket.io": "0.9.6"
  }
And now you need to install these modules before you could use it. To do the installation type in the following command in your command prompt after you change the directory to the chat folder.

npm install

And so now the modules got installed and lets get started with some node code.

Create a file called server.js in your chat folder. You would be creating your server in this file. We would be using the connect module to create the server. This would redirect your server to the index.html file in a folder named public which you need to create. Type in the following code to create the server and redirect it.
var connect = require('connect');
var io = require('socket.io');
var app = connect().use(connect.static('public')).listen(8080);
var chat = io.listen(app);
Now just create a folder named public and create a file named index.html in that folder. Just type in some sample content in it and lets test your app to see if that works well. To start your application type in the following command in your terminal after changing the current directory to the chat folder.

node server.js

Now open up your browser and navigate to http://localhost:8080 and this should display the index.html file of your public folder.

And now lets make our page to look like a public chatroom. Just add the following code in your index.html file.
<title>Chat Room - Node JS</title>
<link rel = "stylesheet" href = "style.css">
<script src = "/socket.io/socket.io.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body>
<div class = "room">
<div class = "messages">
<b><p class = "text" style = "color: #0072c5;">Messages</p></b><hr>
<div class = "text" id = "chat">
</div>
</div>
<textarea class = "msginput" id = "chattr" placeholder = "Hit Enter To Send Message" onkeydown = "check(event.which)"></textarea>
</div>
</body>
And to do some styling add the following code in your style..css file.
body {
background-color: #f1f1f1;
}
.room {
background-color: #fff;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
width: 70%;
height: 70%;
padding: 2%;
}
.msginput {
resize: none;
width: 95%; font-family: Arial;
font-size: 16px;
padding: 10px;
border-radius: 10px;
position: absolute;
bottom: 10px;
left: 2%;
}
.messages {
border: solid #d1d1d1 1px;
padding: 10px;
height: 80%;
overflow-y: scroll;
}
.text {
font-family: Arial; }
Ok so now the markup part is done and lets get started with some socket.io code. So what is socket.io ? It is used for web socket programming in Node JS. Web sockets are bidirectional and full duplex that allows you to send and receive data back and forth between the server and the client simultaneously unlike the http protocol.

Socket.io allows you to emit and receive events between the client and the server. You can emit an on the server side and the client can listen for that and do some function or a client can emit an event and you can listen for that event on the server side. So we first need to create a variable that contains the sockets object. And we could use the connect event that is already present in the module to run a function when a new client connects to the site. So type in the following code in your index.html file.
<script src = "/socket.io/socket.io.js"></script>
<script type = "text/javascript">
var chat = io.connect();
var nickname;
chat.on('connect', function(){
              console.log('New user connected');
});
</script>

Try running this using the node server.js command in your terminal. Now open up your browser and redirect to http://localhost:8080. And then open up your terminal and you would see the message New user connected. We now need to create a prompt that asks the user to enter their name. After getting the name of the user we would then fire an event from the client that would contain the name of user. On the server side we would just listen for that event and would broadcast that message to all the sockets connected at that time. We will be dealing with the server side events at the end. To do that modify the above code as follows :
<script type = "text/javascript">
var chat = io.connect();
var nickname;
chat.on('connect', function(){
nickname = prompt("Enter Your Name :");
chat.emit('message', {message: "<i><b style = 'color: #0072c5;'>" + nickname + "</b> Joined</i><hr style = 'opacity: 0.3;'>"});
});
</script>
Instead of sending just a boring plain text I have just formatted it with some html tags make it look good. Alright. You could see that in the index.html we already had created a chat room look with a textarea with id chattr. We would just check every character that the user enters and check for him hitting the return key. Once he hits the return key we would fire the chat event and would send the message that the user entered along with the event. If you had noticed above we would have created an onkeydown event in the textarea that fires a check() function along with the event parameter. So lets create the check function now. Using this we would check the key code of the key pressed. And if it matches the keycode of return key (i.e. 13) we would fire the chat event. Add the following code to the script tag.
function check(e){
if(e==13){
chat.emit('chat', {message: nickname + ": " + $('#chattr').val()});
$("#chattr").val("");
    }
}
Ok so now lets go to our server side and lets listen for the events that we fired from our client. To do that add the following code to your server.js file.
chat.sockets.on('connection', function(client){
client.on('message', function(data){
chat.sockets.emit('message', {message: data.message});
});
client.on('chat', function(data){
chat.sockets.emit('message', {message: data.message + "<hr style = 'opacity: 0.3;'>"});
});
client.on('disconnect', function(){
   chat.sockets.emit('message', {message: "<p style = 'color: red;'>An User Left.</p> <hr style = 'opacity: 0.3;'>"});
});
}); 

You could notice that we are emitting another event called message event to all the sockets while listening to the chat event. We would be listening to that event on the client side again and would be displaying it to the user. And we also are emitting an event when the user gets disconnected which displays a message An User Left to all the users connected. So now our final job would be to display the message to the user. To do that add the following code within the script tag of your index.html file.
chat.on('message', function(data){
$("#chat").append(data.message);
});
We have just appended the div with id chat with the message that an user sends. So this would complete your application.

With all these said you could see that Node JS is already becoming too popular due to its asynchronous code. So it is a must to learn if you are going to be one of those awesome web developers out there. I used the following book learn Node JS and its really awesome. So why don't you do that too. You can buy it from the link below.

 You can find the code in the link below.

 Live Demo
Download Source Code




Try opening the live demo in a couple of tabs and test it out. And so that's the end of the post. Hope it helped out. Happy Node-ing :)

Categories: , ,


A High School graduate. Addicted to Music, Web Design, Blogging, Web Development and Photoshop. Loves CSS a lot. Has 3 years of experience with blogging and 2 years with Web Design and Development.

0 comments:

Post a Comment