28
Sat, Dec
0 New Articles

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

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: