Create a WebSocket Server Using Node.js

Posted by: Mahesh Sabnis , on 12/10/2015, in Category Node.js
Views: 19090
Abstract: Node.js provides a simple and easy to use WebSocket Server that helps to pair up with the HTML5 WebSocket on the client and enable real-time communication.

This is the era of Real-time apps. Be it a weather tool, gaming, news or any other service, getting information real-time is an in-thing now. HTML5 introduced a new standard for real-time communication called WebSocket. Similarly on the server-end you needed something that could pair with WebSockets and enable real-time communication. Node.js provides several modules for managing server side processing. There are modules for creating Web Server using code and even for creating a WebSocket Server.

 

A WebSocket Server is a TCP application listening on any port of the server. This provides for an efficient communication “channel” between clients and the server. The WebSocket Server can be written using any server-side language. Since Node.js provides server side processing for JavaScript, we can use it for Socket Programming.

In this article, we will be create a WebSocket server using a module provided by Node.js. We will then implement a simple communication between the HTML 5 client and the WebSocket Server.

The ws module

In Node.js we have the ws module for creating WebSocket Server using code. This provides high performance for communication over sockets. This Module provides events and functions for opening, sending, receiving and closing messages.

WebSocket Server Implementation

We will make use of Visual Studio Code as our editor. This is a new FREE IDE provided for developing modern Web and cloud applications. This IDE can be downloaded from here. We can make use of this IDE for building ASP.NET 5, Node.js, and various applications. You also need NTVS (Node Tools for Visual Studio). Here’s an entire article on the same Node Tools for Visual Studio.

Step 1: Create a folder of the name VSCodeWebSocketServer on your hard drive. We will use this folder for storing our application files.

Step 2: Open Visual Studio Code. Click on File > Open Folder and navigate to the VSCodeWebSocketServer folder. Select this folder. You should now see options for creating a new folder inside VSCodeWebSocketServer as shown in the following image:

vscode-newfolder

Name this folder as Scripts, we will use this folder for storing our JavaScript application file. Add a new folder of the name Pages in the VSCodeWebSocketServer for storing the Html file.

Step 3: Open the Node.js Command Prompt, (This will be available to us after installing Node.js tools). Run following commands from the command prompt:

npm install -g tsd

This will install TypeScript Definition for our application so that we can install and use other Node.js modules

tsd query node --action install

This command will provide Node.js intellisense.

tsd query ws –action install

This command will install the ws module. This module provides APIs for creating WebSocket Server. After installing this module the following result will be displayed

 

install-tsd

Step 4: In the Scripts folder, add a new JavaScript file of the name app.js, add the following code in this file

//1.
var webSocketServer = require('ws').Server;
var http = require('http');
var fs = require('fs');


//2.
var webSocketServerObject = new webSocketServer({ port: 9060 });

//3.
webSocketServerObject.on('connection', function (socketObject) {

    socketObject.on('message', function (message) {
        console.log('The' + message + 'Message Received from \n from IP ' + socketObject.upgradeReq.connection.remoteAddress);

        socketObject.send("Received " + message);
    });

    socketObject.on('close', function (c, d) {
        console.log('Disconnect ' + c + ' -- ' + d);
    });
});

//4.
var server = http.createServer(function (req, resp) {

    fs.readFile("../Pages/Client.html", function (error, pgResp) {
        if (error) {
            resp.writeHead(404);
            resp.write('Contents you are looking are Not Found');
        } else {
            resp.writeHead(200, { 'Content-Type': 'text/html' });
            resp.end(pgResp);
        }
    });
});
//5.
server.listen(5050);

console.log('Server started');

The above code has the following specifications (Note: Comment numbers applying on code matches with the following numbering)

1. Load modules for creating WebSocket Server, WebServer, and the File IO.

2. Define an instance of the WebSocket and register the port 9060 for it.

3. Register the connection event which will be used by the WebSocket server for managing messaging through it. This event provides Socket object, using which Messages can be used for processing. The Send () function is used to send message through the socket. The close event is used to disconnect the messaging.

4. Create a web server to read the Html file from the Pages folder and respond to the request made by the client.

5. Start listening on the port 5050.

 

Step 5: In the Pages folder, add a new file of the name client.html. This file will contain HTML markup and HTML5 WebSocket object to manage the communication with the WebSocket Server created in the previous step. Add the following code (HTML and JavaScript) in the html page

<html>
<head>
    <title>The Socket Server</title>
    https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js
</head>
<body>
    <h1>The Communication with Socket</h1>
    Message:<input type='text' id="message">
    <br />
    <input type="button" id="btnsend" value="Send" />
    
 
$(document).ready(function(){ //1. var ws = new WebSocket("ws://localhost:9060"); var communication = ""; //2. $("#btnsend").on('click',function(){ var message = $("#message").val(); ws.send(message); communication += 'Send Message ' + message + " "; $("#dvMessage").html(communication); }); //3. ws.onmessage = function(evt){ communication += 'Received Message ' + evt.data+ " "; $("#dvMessage").html(communication); }; //4. ws.onclose = function(evt){ communication += 'Conenction Closed ' + evt.code + " " + e,type+ " "; $("#dvMessage").html(communication); }; //5. ws.onerror = function(evt){ communication += 'Error Occured ' + evt.data+ " "; $("#dvMessage").html(communication); }; }); </body> </html>

The above Html contains the CDN reference for jQuery which is used to execute jQuery code. The Html markup is provided for TextBox and button. The body contains jQuery for Socket programming. The following points describe the code. (Note: The Comments number matches with the numbering inside the code)

1. Create an instance of the WebSocket by defining the URL for the Port on which WebSocket Server is ready to accept incoming messages. In our case web have use port 8080.

2. The click event for the button calls the send() function of the WebSocket object and sends the message entered in the textbox to the server.

3. Onmessage event is used to listen to the message sent by socket server.

4. Onclose event is used to listen to the connection close event.

5. Onerror is used to take necessary action when an error occurs during messaging.

Step 6: To execute the application, right click on app.js in Visual Studio Code and select the option Open in Command Prompt. This will open the command prompt. Add the following command in the Command Prompt

Node app

The following result will be displayed:

server-started

Open any browser and enter the following address in the address bar:

http://localhost:5050/Pages/Client.html

socket-comm

Enter some message in the TextBox and click on the Send button, the result will be as shown in the following image:

socket-comm-result

Visit back the running Command prompt and the following result will be displayed

 

result

This shows the message received from the client and its IP address.

Conclusion

Node.js provides a simple and easy to use WebSocket Server that helps to pair up with the HTML5 WebSocket on the client and thereby enables real-time communication.

Download the entire source code of this article (Github)

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Mahesh Sabnis is a DotNetCurry author and Microsoft MVP having over 17 years of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions). Follow him on twitter @maheshdotnet


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!

Categories

JOIN OUR COMMUNITY

POPULAR ARTICLES

FREE .NET MAGAZINES

Free DNC .NET Magazine

Tags

JQUERY COOKBOOK

jQuery CookBook