Asynchronous server-client communication with websockets and node.js

Overview

In our blogpost today we will show you an example of using node.js to provide a simple echo server which will interact asynchronously with a client html page on Windows OS. This way, we avoid polling for updates in specific time intervals and it is possible to initiate communication from either the client or the server at any time.

What is a Websocket?

WebSocket is a technology that enables interactive communication between a user's browser and a server. This special communication channel provides a bi-directional, full-duplex, constant connection from a browser to a server. As a result, a browser can send messages to a server and receive event-driven responses without the client needing to poll the server at certain intervals. Once a connection is established, it stays open until one of the two parts decides to close it and the client or server can send a message to the other at any given time. This makes websocket ideal for real-time apps in which data needs to be available immediately.

Prerequisites

Before moving on with our example, please make sure that you have downloaded and installed nodejs. Once nodejs is installed, open a command prompt and navigate to the corresponding folder so that you can install ws module in your node environment.

cd C:\Program Files\nodejs
npm install ws

Now you are ready to create your websocket server!

Implementation of websocket server and client

Now let's get to the most interesting part; the implementation of the websocket server. Here's how the server code will look:

Echo.js server
var WebSocketServer = require('ws').Server

// Create an instance of websocket server.
var wss = new WebSocketServer({host: '127.0.0.1',port: 9000});

console.log('New server created, waiting for connections...');
// Add the connection listener that will be triggered once the connection is established.
wss.on('connection', function(ws) {
    console.log('Server was connected.');
    //  Add the listener for that particular websocket connection instance.
    ws.on('message', function(message) {
        console.log('Server received message: %s', message);
        // Send back the message that we receive from the browser
        ws.send(message);
    });  
});

The sequence of the server's code is as follows:

  • Create an instance of websocket server and define the port that it will listen to.
  • Add the connection listener that will be triggered once the connection is established.
  • Add the listener for that particular websocket connection instance that can be used for many purposes, in our case for sending messages.
  • Send back the message that we receive from the browser through the websocket instance.

After implementing the server, we will continue by writing the client-side code in Javascript. The sequence of the code will be the following:

  • First we have to open the connection with the server.
  • Once the connection is opened successfully we log a message to the screen.
  • Then we wait for user input. As soon as it is received, we send it to the websocket server.
  • If a message is received from the server, we display it on the screen.
  • When the connection is closed, we inform the user.
Echo.html test page
<!DOCTYPE html>
<html>
    <head>
        <title>Websocket test page</title>
    </head>
    <body>

        <input id="entry">
        <button id="send">Send</button>
        <pre id="log"></pre>
        <script>

        // Function that helps us log message to the screen.
        function log(msg) {
            document.getElementById('log').innerText += msg + '\n';
            console.log(msg);
         }

        // Setup websocket with callbacks.
        // Open the connection with the server.
        var ws = new WebSocket('ws://localhost:9000/');

        // Log a message when connection is successful.
        ws.onopen = function() {
            log('Connected to server');
        };

        // Waiting for user input.
        document.getElementById('send').onclick = function () {
            var msgSend= document.getElementById('entry').value ;
            log ("Browser sends: " + msgSend);
                //Once user's input is received, we send it to the server.
                ws.send (msgSend);
        }

        // When a message from server is received, we display it on the screen.
        ws.onmessage = function(evt) {
            var msgReceived = evt.data;
            log ("Websocket server responds: " + msgReceived);
        }

        // As soon as the connection is closed, we inform the user.
        ws.onclose = function() {
            log('Disconnected from server');
        };
        </script>
    </body>
</html>

Test your Websocket server and client

Once we have written our code, it is time to test it. To achieve this, we need to start our node.js Echo.js server. Open a command prompt and navigate to the folder where node.exe is located.
cd C:\Program Files\nodejs
Then, start the server by running the command:
node.exe Echo.js

You will now see on your cmd that the server is running and waiting for connections:

EchojsServer

Once you are sure that the server started, it is time to set up the client. Drag and drop your Echo.html page on your browser.

EchoHtml

Verify that the server detected the connection:

EchojsServerConnected

Go back to the browser, type a message and click on Send button. Verify that your websocket server received the message and send it back to the browser.

EchojsServerSend

EchoHtmlSendReceive

That's all!

WebSocket technology provides a simple way to do fast, robust and efficient communication between the client and the server. Remember, as amazing as websocket may be, websocket is a protocol and evolving standard. This means that each browser implementation may vary so keep up to date, do good research and test before using it! Thanks for stopping by and reading our post. We're looking forward for your feedback!