[et_pb_section bb_built=”1″ fullwidth=”on” specialty=”off” _builder_version=”3.0.64″ next_background_color=”#000000″][et_pb_fullwidth_post_title admin_label=”Blog Post Header” _builder_version=”3.17.2″ title=”off” categories=”off” comments=”off” featured_placement=”background” parallax_method=”off” text_orientation=”center” module_class=”blog_post_header” title_font_size=”60px” background_blend=”saturation” title_font=”Raleway|on|||” title_text_color=”#274060″ title_letter_spacing=”2px” meta_font=”Raleway||||” meta_font_size=”20″ meta_text_color=”#274060″ meta_letter_spacing=”2px” background_color=”rgba(144,144,144,0.39)” meta=”off” author=”off” /][/et_pb_section][et_pb_section bb_built=”1″ _builder_version=”3.0.63″ prev_background_color=”#000000″][et_pb_row _builder_version=”3.0.63″][et_pb_column type=”4_4″][et_pb_text admin_label=”Blog Post” _builder_version=”3.0.69″ background_layout=”light” text_orientation=”left” border_style=”solid” saved_tabs=”all” global_module=”30698″]

Originally published: MC Press Online on 5/29/15

“Wow, that was significantly simpler than I thought it would be,” said no web programmer ever.

I am often in the camp of wishing things were simpler with web development, specifically the link between the browser and server, so that I don’t have to think as much about the underlying technology and can focus more on meeting the business need. Many technologies have made strides in this area over the years with concepts of convention over configuration (thank you, Ruby on Rails). Today, I am tooting the horn of JavaScript and Node.js in the implementation of HTML5 WebSockets.

Wikipedia describes HTML5 WebSockets as “a protocol providing full-duplex communication channels over a single TCP connection”.

HTML5 is just a specification, not an implementation. It’s every technology stack’s responsibility to implement said spec and not only make everything adhere to the spec but also put some amount of focus on making usage easy for the web developer. In the case of Node.js, we have a Node Package Module (NPM) named socket.io that implements HTML5 WebSockets with excellence to the point of being surprisingly simple and easy to use.

Our goal in this article is to use socket.io to create a chat application using HTML5 WebSockets, as shown in Figure 1. The concept is that two browser clients will obtain a WebSocket connection to the server so chat messages entered in one browser are delivered from the server to the client in another browser without the client polling the server. It is important to note the lack of polling in that last sentence. That’s how things were done in the past. Now, the server can initiate communication down to the client. Very cool!

Here's a Socket.io chat application.
Here’s a Socket.io chat application.

Before we move on to writing the chat application, it would be good to [[review how to set up and use your Node.js environment(*Note: post “Node.js is Here. What to Do?”)]].

Open up an IBM i shell prompt and create a new directory named nodejs_websocket and cd (change directory) into it, as shown below.

$ mkdir nodejs_websocket && cd nodejs_websocket

Next, we want to initialize the nodejs_websocket folder as a Node.js application by running the following command. This will prompt you for a few questions and in the end create a package.json file that is used to store information about the application. More on package.json in a bit.

$ npm init

Now, install expressjs using the following command. Specifying --save will cause this to be placed as an application dependency in the package.json file.

$ npm install express --save
npm WARN package.json nodejs_websocket@0.0.0 No repository field.
npm WARN package.json nodejs_websocket@0.0.0 No README data
express@4.12.3 node_modules/express
├── merge-descriptors@1.0.0
├── methods@1.1.1
├── cookie-signature@1.0.6
├── fresh@0.2.4
├── cookie@0.1.2
├── utils-merge@1.0.0
├── escape-html@1.0.1
├── range-parser@1.0.2
├── content-type@1.0.1
├── finalhandler@0.3.4
├── parseurl@1.3.0
├── vary@1.0.0
├── serve-static@1.9.2
├── content-disposition@0.5.0
├── path-to-regexp@0.1.3
├── depd@1.0.1
├── on-finished@2.2.0 (ee-first@1.1.0)
├── qs@2.4.1
├── debug@2.1.3 (ms@0.7.0)
├── proxy-addr@1.0.7 (forwarded@0.1.0, ipaddr.js@0.1.9)
├── etag@1.5.1 (crc@3.2.1)
├── send@0.12.2 (destroy@1.0.3, ms@0.7.0, mime@1.3.4)
├── accepts@1.2.5 (negotiator@0.5.1, mime-types@2.0.10)
└── type-is@1.6.1 (media-typer@0.3.0, mime-types@2.0.10)

Now, install socket.io with command “npm install socket.io --save“. At this point, your package.json file should look similar to the following. Notice the two entries in dependencies have both modules we just installed.

  "name": "nodejs_websocket",
  "version": "0.0.0",
  "description": "HTML5 websocket example",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  "author": "KrengelTech",
  "license": "ISC",
  "dependencies": {
    "express": "^4.12.3",
    "socket.io": "^1.3.5"

Next, we will create the two files necessary for this application using the touch command, namely app.js and index.html, as shown below:

$ touch app.js index.html

Below, we have the entirety of the app.js code, which resides entirely on the server. The first three lines are bringing in outside functionality, much like a /COPY in RPG. Line 5 is waiting for requests to the root of the domain and, once invoked, will send the index.html file down to the browser.

var app = require('express')();
var http = require('http').Server(app);
var io   = require('socket.io')(http);

app.get('/', function(req, res){

io.on('connection', function(server){
  server.on('disconnect', function(){
    console.log('user disconnected');
  server.on('chat message', function(msg){
    io.emit('chat message', msg);

http.listen(8001, function(){
  console.log('listening on *:8002');

Line 9 is listening for the connection event and is where WebSocket type functionality is introduced. The connection event occurs in, and is initiated from, the client (or rather from within index.html). Below is the entirety of the index.html file. Lines 1 through 15 aren’t necessary to discuss. The important part starts when we first include the client-side socket.io library from its Content Delivery Network (CDN). I say client-side library to call out the fact that while socket.io is one tool, it has two parts: one for the client-side and the other for the server-side. Line 23 is where the WebSocket connection is initiated to the server. Once the connection is made, both the server and client go into a wait state where either can initiate communication to the other. There is one exception to that last sentence. If the client doesn’t support WebSockets, then the polling of client-to-server approach will be employed.

<!doctype html>
      * { margin: 0; padding: 0; box-sizing: border-box; }
      body { font: 13px Helvetica, Arial; }
      form { background: #000; padding: 3px; position: fixed; bottom: 0; 01 width: 100%; }
      form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
      form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages li { padding: 5px 10px; }
      #messages li:nth-child(odd) { background: #eee; }
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    <script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
    <script src="http://code.jquery.com/jquery-1.11.1.js"></script>
      var client = io();
        client.emit('chat message', $('#m').val());
        return false;
      client.on('chat message', function(msg){

Line 24 is jQuery listening for the form to be submitted. This is not part of WebSockets, but it’s important for ease of client-side programming. Line 25 is important. This is where the app is “emitting” a message to the server. Looking back at app.js, there is line 13 “listening” for “chat message” events. When it receives one, it then emits messages to all other browser clients that are listening for the same “chat message” event. The emitting of a new message from server to clients is on line 14. Socket.io does an excellent job of hiding complexity if you ask me. Going back to index.html line 29, we can see the “chat message” being listened for. When a message is received, jQuery is used to obtain reference to #messages, adding the entry to the bottom. At this point, the full loop of communication is complete and all users see the new chat message.

I purposely didn’t go into details of the WebSocket technology in this article. Sometimes we have the luxury of not needing an intimate understanding of the technology going on under the covers. I believe this is the case with socket.io. Hopefully, this gives you a good idea of one way WebSockets can be used and maybe even sparks some ideas of your own.

Stay tuned for an article introducing Git on IBM i!


One Response