Websockets using Node.js on openshfit platform

Node.js is getting popular these days. Node.js is best for developing realtime web applications like multiplayer games, real time chat applications. This will guide you how you can use node.js to create a simple chat application. And we will also host the application to openshift cloud platform.

What is nodejs?

WebSocket is the http protocol which provides full duplex communication between modern web browsers and web servers over a single TCP connection. Although it is mostly used to communicate between browsers and web servers, it can be also used from other types of clients for eg: android ios apps, desktop clients etc.

WebSockets at the servers are initialised by http as upgrade process and requests are forwarded to the relevant web-socket handling process. Same http port 80 can be used to communicate so no firewall issues to communicate to the server.

In this tutorial we will create simple node application using express and web sockets to handle both static html pages and websocket requests on the same 8080 port. Off course you can change the port to 80 on live environment.

What is node.js?

Node.js is a server platform built on the google javascript runtime environment. Node.js helps easily build fast, scalable, network applications like multiplayer games, realtime chat applications and many more.

Node.js uses non-blocking IO model which is best suited for realtime network application. Although node.js is a single threaded server application, it can handle really lots of requests because of its non-blocking IO mode.

First create a simple web server using node.js to handle web requests.

We will use express library to create web server that serve static html contents.

Code to create web server on node.js

server.js
http = require('http');
var express = require('express');
var fs      = require('fs');

var WebApp = function() {
    var self = this;
    self.setupVariables = function() {
        self.ipaddress = process.env.OPENSHIFT_NODEJS_IP;
        self.port      = process.env.OPENSHIFT_NODEJS_PORT || 8080;

        if (typeof self.ipaddress === "undefined") {
            self.ipaddress = "127.0.0.1";
        };
    };
    self.initializeServer = function() {
        self.app = express();
        self.server= http.createServer(self.app);
        self.app.use(express.static(__dirname + '/'));
    };

    self.initialize = function() {
        self.setupVariables();
        self.initializeServer();
    };

    self.start = function() {
        self.server.listen(self.port, self.ipaddress, function() {
            console.log('%s: Node server started on %s:%d ...',
                        Date(Date.now() ), self.ipaddress, self.port);
        });
    };

}; 

var zapp = new WebApp();
zapp.initialize();
zapp.start();

Now its time to use ws library to crete web socket on the server. With web sockets we can have client always connected to the server and retrieve data as available on the server rather than browser checking for new data.

Our web server is ready with support of web socket.

Now its time to create client. We will use HTML5 WebSocket to have persistence connection to the web server we created earlier.

index.html

		<!DOCTYPE HTML>
<html>
   <head>
      <title>
         Chat
     </title>
      <script src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>
      </head>

   <body>
      <div>
            
            <h1> A Chat application with Node.js and Socket.io </h1>
            
         <div id="chatEntries"> </div>
         <div id="chatControls">
            <input type="text"  id="messageInput"/>
            <button id="submit"> Send </button>
        </div>
    </div>
    </body>
    <script>
    var host=location.origin.replace(/^http/, 'ws')
var ws = new WebSocket(host);
ws.onmessage = function (event) {
        console.log(event.data);
       var data= event.data;
       addMessage(data,'server'); 
};
ws.onopen= function (event){
    console.log('client connected' + event);

}
ws.onclose = function()
     { 
        // websocket is closed.
        console.log("Connection is closed..."); 
     };
function addMessage(msg, pseudo) {
   $("#chatEntries").append('<div class="message"><p>' + pseudo + ' : ' + msg + '</p></div>');
}

function sentMessage() {
   if ($('#messageInput').val() != "") 
   {
      ws.send($('#messageInput').val());
      $('#messageInput').val('');
   }
}

$(function() {
   $("#submit").click(function() {sentMessage();});
});
    </script>
</html> 

Which port to use?

Yo can use any port for web socket to listen but open shift only allows ports 80 and 8000 which are accessible from outside (publicly). But you still you have to listen to port defined as $OPENSHIFT_NODEJS_PORT which is 8080.

Here is how port is forwarded to your application in open shift platform.

Normal http request : port 80 => port 8080 Web socket http request : port 8000 => port 8080

So we are binding the same port 8080 on both express http server and web socket on our server.js node application.

Host to the openshift cloud

You need to create the account on openshfit cloud platform. It is free and gives you some decent resources to test your app.

Here is the site that is hosted on openshift using node and web socket.


Like us

See also

How to create datagridview custom column

How to create custom column for datagridview using C#