Real-time web with Node.js & Socket.io

If you are a .net developer, you may be familiar with ASP.net SignalR for real-time web development. It's one of the coolest libraries for ASP.net that allows bi-directional communication between a server and a client. For more details refer http://www.asp.net/signalr

This blog post is an intro to use Node.js and Socket.io to achieve real-time web communication with pure JavaScript using a simple chat program example. Socket.io is a library that makes our lives easy to work with web sockets. Of course, in the Javascript world, there are hundred other libraries available to implement web sockets, examplesBut i like the simplicity of Socket.io. 

Step 01 : Setting up Node.js

Depending on the operating system you are using, download Node.js from the official site here. Installation process of both Windows and OSX is pretty much the same. Double click the setup file and follow the straightforward instruction. For Linux, either you can download the .tar file or download the binary to compile and run. Nodejs is preferred to use in Linux environment however for this example let's use Windows version. 

Once you have installed nodejs on windows, open up a command prompt and type,
node --version
If it shows a command not recognized error message, you might need to add node.js installed folder in the Program Files to the environment variables. Otherwise it will show the current nodejs version. Together with nodejs it has installed npm which is the package manager for nodejs. npm let us to install dependent node modules very easily via the command prompt. You can verify npm installation by typing following command in a command prompt,
npm --version 
Step 02 : Installing Dependencies


As we are going to use Socket.io with nodejs, we need to install socket.io package. Create a new folder. Inside that, create a json file called package.json. Open it with nodepad++ or any other text editor. Add following json data.

Set name and the version values as you prefer. By setting private to true, it avoids accidental publishing your node app as a npm module. Dependencies is very important. Make sure to spell them correctly. The version numbers refers to the currently installed socket.io and express packages.  That's it! 

Now open the project directory in a command prompt and enter the command,
npm install
This will install all the dependent modules in the node_modules folder inside project directory. 

Step 03 : Creating app.js & index.html

Now that we have all the modules we need, let's create the server. In the project directory create a new file and rename it app.js. Open with a text editor and add following code. 

I almost forgot to mention that we are using express as our web framework for this simple chat application. It's lightweight but powerful. more info.
Next up we need setup routes. So that we can direct users to our index.html page. I am adding some more code to the app.js.

Now anyone who enters the address, http://localhost:3000/ will be served with index.html. Let's take a look at completed index.html.

If you are familiar with RPC(Remote Procedure Calls) implementation in Java or any other languages you can easily understand the above code. Simply, the client needs to talk to the server. So he needs to know about the methods or functions available in the server. Similarly, when server needs to send a response to the client, server should know about the functions exist in the client. Once they get to know each others functions they can pass messages between each other. Client side proxy or "stub" contains the information about the server functions. Server side proxy or "skeleton" has the information of client side functions. Thus, both server and client knows the function names and their parameters to communicate with each other.
socket.emit("send",$("#msg").val()); in line 25, 
client sends whatever typed in the input box to the function "send" defined in the server. And then in line 30, client receive the data from the server to his client function "receive". And then it appends the data in the "chatbox" div.

Step 04 : Completing app.js

Here you can find the definition of the "send" function in the server and how it calls the client side function "receive" by passing the parameters.

Take a look at the following diagram. It is a graphical representation of how node.js and socket.io communicate among clients and the server.



Socket.io allows following broadcasting methods.
1. Broadcast to all the clients including the requested client. (as shown in the example)
io.sockets.emit('receive',data);

2. Broadcast to all other clients except the requested client.
   socket.broadcast.emit('receive',data);

3. Send result only to the requested client. 
   socket.emit('receive',data);


4. Broadcasting to a specific set of clients. (we can create groups!)

    io.sockets.in("mygroup").emit('receive',data);


That's it! This is how we create a simple chat application using node.js and socket.io.

Cheers :)

Comments

  1. I have gone through your blog, it was very much useful for me and because of your blog, and also I gained many unknown information, the way you have clearly explained is really fantastic. Kindly post more like this, Thank You.
    Aviation Academy in Chennai
    Aviation Courses in Chennai
    best aviation academy in Chennai
    aviation institute in Chennai

    ReplyDelete

  2. Thank you for sharing the article. The data that you provided in the blog is informative and effective. Best Devops Training Institute

    ReplyDelete
  3. Thanks for sharing.
    very useful information, the post shared was very nice.
    Full Stack Online Training

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
  5. Excellent Blog! I would Thanks for sharing this wonderful content.its very useful to us.it was very much useful for me and because of your blog, and also I gained many unknown information, the way you have clearly explained is really fantastic.
    oracle training in chennai

    oracle training institute in chennai

    oracle training in bangalore

    oracle training in hyderabad

    oracle training

    hadoop training in chennai

    hadoop training in bangalore

    ReplyDelete

Post a Comment

Popular posts from this blog

Dependency Injection in ASP.NET MVC 5 with StructureMap

First Look at AngularJS 2.0