TechTip: Node.js Is Genius with WebSockets

Web Languages
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

HTML5 brought with it a number of new features, and WebSockets stands out as a top necessity to browser-based apps.

 

"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!

 

052915BartellFigure1

Figure 1: 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.

 

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

This email address is being protected from spambots. You need JavaScript enabled to view it..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)

??? This email address is being protected from spambots. You need JavaScript enabled to view it..2 (destroy@1.0.3, ms@0.7.0, mime@1.3.4)

??? accepts@1.2.5 (negotiator@0.5.1, This email address is being protected from spambots. You need JavaScript enabled to view it.)

??? type-is@1.6.1 (media-typer@0.3.0, This email address is being protected from spambots. You need JavaScript enabled to view it.)

 

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.

 

01 var app = require('express')();

02 var http = require('http').Server(app);

03 var io   = require('socket.io')(http);

04

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

06   res.sendfile('index.html');

07 });

08

09 io.on('connection', function(server){

10   server.on('disconnect', function(){

11     console.log('user disconnected');

12   });

13   server.on('chat message', function(msg){

14     io.emit('chat message', msg);

15   });

16 });

17

18 http.listen(8001, function(){

19   console.log('listening on *:8002');

20 });

 

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.

 

01 <!doctype html>

02 <html>

03   <head>

04     <style>

05       * { margin: 0; padding: 0; box-sizing: border-box; }

06       body { font: 13px Helvetica, Arial; }

07       form { background: #000; padding: 3px; position: fixed; bottom: 0; 01 width: 100%; }

08       form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }

09       form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }

10     #messages { list-style-type: none; margin: 0; padding: 0; }

11       #messages li { padding: 5px 10px; }

12       #messages li:nth-child(odd) { background: #eee; }

13     </style>

14   </head>

15 <body>

16     <ul id="messages"></ul>

17     <form action="">

18       <input id="m" autocomplete="off" /><button>Send</button>

19     </form>

20     <script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>

21     <script src="http://code.jquery.com/jquery-1.11.1.js"></script>

22     <script>

23       var client = io();

24       $('form').submit(function(){

25         client.emit('chat message', $('#m').val());

26         $('#m').val('');

27         return false;

28       });

29       client.on('chat message', function(msg){

30         $('#messages').append($('<li>').text(msg));

31       });

32     </script>

33   </body>

34 </html>

 

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!

BLOG COMMENTS POWERED BY DISQUS