Network and WebSocket
Programming (HTML 5)
ROBERT V. OCAMPO JR.,
Presenter
Pangasinan State University
College of Computing Studies – IT Department
Integrative Programming and Technologies 101 Module 6
Coverage
• The WebSocket API
- This is to establish the parties of the Websocket communication and data transmission,
namely server and client.
• Configuration of the Server
• Data Transfer – Sending, Receiving and Decoding
• Error Handling for the Websockets
Integrative Programming and Technologies 101
WebSocket API
• Any HTML5 web client is a combination of structure, styling, and
programming logic.
• Markup: The markup defines the structure of your web application. It is a
set of XML tags that lets you specify the hierarchy of the visual elements
within an HTML document.
Integrative Programming and Technologies 101
WebSocket API
Here is a simple example of HTML5 markup <!DOCTYPE html>
code that generates the essential elements
<head>
for our chatting app: a text field, two buttons,
and a label. The text field is used for typing <title>HTML5 WebSockets</title>
our message, the first button will send the </head>
message, the second button will terminate <body>
the chat, and the label will display the <h1> HTML5 WebSocket chat. </h1>
interactions coming from the server: <input type="text" id="text-view" />
<input type="button" id="send-button" value="Send!"
/>
<input type="button" id="stop-button" value="Stop" />
<br/>
<label id="status-label">Status</label>
</body>
Integrative Programming and Technologies 101
WebSocket API
Styling: In order to display colors, h1 {
color: blue;
backgrounds, fonts, alignments, and so
text-align: center;
on, you need to be familiar with
font-family: "Helvetica Neue", Arial,
Cascading Style Sheets (CSS). Example: Sans-Serif;
font-size: 1em;
Integrative Programming and Technologies 101
WebSocket API
Logic: This an event handling and user actions. var buttonSend = document.getElementById("send-
button");
Example: JavaScript.
buttonSend.onclick = function() {
• JavaScript is a scripting programming language console.log("Button clicked!");
that lets you control and alter the behavior of
your web app according to the accompanying }
actions.
• Using JavaScript, you can handle button clicks, Explanation: The first line searches the
document tree, finds the element named action-
page loads, apply addition styling, add special button and stores it in an object named
effects, or even fetch data from web services. buttonSend. Then, a function is assigned to the
onclick event of the button. The body of the
• Using JavaScript, you can create objects, assign function is executed every time the button is
clicked on.
them properties and methods, and raise and
catch events when something occurs.
Integrative Programming and Technologies 101
WebSocket API Overview
API, which stands for Application Programming Interface,
is a set of objects, methods, and routines that let you
interact with the underlying layer of functionality.
Considering the WebSocket protocol, its API includes the
WebSocket primary object, events, methods, and attributes.
Translating these characteristics into actions, the
WebSocket API allows you to connect to a local or remote
server, listen for messages, send data, and close the
connection.
Integrative Programming and Technologies 101
WebSocket API Overview – Browser Support
JavaScript provides an easy way to find out whether The window.WebSocket statement indicates
a browser can execute WebSocket-specific code: whether the WebSocket protocol is implemented in
the browser. The following statements are
if (window.WebSocket) { equivalent:
console.log("WebSockets supported."); window.WebSocket
// Continue with the rest of the WebSockets-specific "WebSocket" in window
functionality…
window["WebSocket"]
}
• Each one of them results in the same validation
else { check. You can also check about any feature
console.log("WebSockets not supported."); support using your browser's developer tools.
alert("Consider updating your browser for a richer
experience.");
• At the time of writing, WebSocket is fully
supported by Internet Explorer 10+, Firefox 20+,
} Chrome 26+, Safari 6+, Opera 12.1+, Safari for
iOS 6+, and Blackberry Browser 7+.
Integrative Programming and Technologies 101
WebSocket API Overview – Object
It's now time to initialize a connection to the server. All we need is to create a WebSocket
JavaScript object, providing the URL to the remote or local server:
var socket = new WebSocket("ws://echo.websocket.org");
When this object is constructed, it immediately opens a connection to the specified server.
Note: The example URL ws://echo.websocket.org is a public address that we can use for
testing and experiments. The Websocket.org server is always up and running and, when it
receives a message, it sends it back to the client! It's all we need in order to ensure that
our client-side application works properly.
Integrative Programming and Technologies 101
WebSocket API Overview – Events
There are four main events in the WebSocket API: Open, Message, Close, and Error.
You can handle them either by implementing the onopen, onmessage,
onclose, and onerror functions respectively, or by using the
addEventListener method. Both ways are almost equivalent for what we
need to do, but the first one is much clearer.
Integrative Programming and Technologies 101
WebSocket API Overview – Events
onopen
The onopen event is raised right after the connection has been successfully established. It means that the initial
handshake between the client and the server has led to a successful first deal and the application is now ready to
transmit data:
socket.onopen = function(event) {
console.log("Connection established.");
// Initialize any resources here and display some user-friendly
messages.
var label = document.getElementById("status-label");
label.innerHTML = "Connection established!";
Integrative Programming and Technologies 101
WebSocket API Overview – Events
onmessage Checking for data types is pretty easy. Here is
how we can display a string response:
The onmessage event is the client's ear to the
server. Whenever the server sends some data, the socket.onmessage = function (event) {
onmessage event is fired. Messages might if (typeof event.data === "string") {
contain plain text, images, or binary data. It's up // If the server has sent text data, then display it.
to you how that data will be interpreted and var label = document.getElementById("status-label");
visualized: label.innerHTML = event.data;
socket.onmessage = function (event) { }
console.log("Data received!");
}
}
Integrative Programming and Technologies 101
WebSocket API Overview – Events
onclose Source Code:
The onclose event marks the end of the conversation. Whenever this event is fired, no
messages can be transferred between the server and the client unless the connection is Ssocket.onclose = function(event) {
reopened. A connection might be terminated due to a number of reasons. It can be closed
by the server, it may be closed by the client using the close() method, or due to TCP console.log("Connection closed.");
errors. var code = event.code;
var reason = event.reason;
You can easily detect the reason the connection was closed by checking the code, reason, var wasClean = event.wasClean;
and wasClean parameters of the event.
var label = document.getElementById("status-label");
if (wasClean) {
The code parameter provides you with a unique number indicating the origin of the label.innerHTML = "Connection closed normally.";
interruption.
}
else {
The reason parameter provides the description of the interruption in a string format. label.innerHTML = "Connection closed with message " + reason +
"(Code: " + code + ")";
Finally, the wasClean parameter indicates whether the connection was closed due to a
}
server decision or due to unexpected network behavior.
}
Integrative Programming and Technologies 101
WebSocket API Overview – Events
onerror
The onerror event is fired when something wrong (usually unexpected behavior or failure) occurs. Note that
onerror is always followed by a connection termination, which is a close event.
A good practice when something bad happens is to inform the user about the unexpected error and probably try
to reconnect:
socket.onclose = function(event) {
console.log("Error occurred.");
// Inform the user about the error.
var label = document.getElementById("status-label");
label.innerHTML = "Error: " + event;
Integrative Programming and Technologies 101
WebSocket API Overview – Actions
• send() Remember that you can send messages only if the connection is open.
This means that we either need to place the send() method inside the
While a connection is open, you can exchange messages with the onopen event handler or check the readyState property. This property
server. The send()method allows you to transfer a variety of data to returns the state of the WebSocket connection. So, the previous
the web server. Here is how we can send a chat message (actually, the snippet should be modified accordingly:
contents of the HTML text field) to everyone in the chat room:
button.onclick = function() {
// Find the text view and the button.
// Send the data if the connection is open.
var textView = document.getElementById("text-view"); if (socket.readyState === WebSocket.OPEN) {
var buttonSend = document.getElementById("send-button"); socket.send(textView.value);
}
// Handle the button click event. }
buttonSend.onclick = function() { After sending the desired data, you can wait for an interaction from
// Send the data!!! the server or close the connection. In our demo example, we leave the
connection open, unless the stop button is clicked on.
socket.send(textView.value);
Integrative Programming and Technologies 101
WebSocket API Overview – Actions & Properties
close()
The close() method stands as a goodbye handshake. It terminates the connection
and no data can be exchanged unless the connection opens again.
Similarly to the previous example, we call the close() method when the user clicks
on the second button:
var textView = document.getElementById("text-view");
var buttonStop = document.getElementById("stop-button");
buttonStop.onclick = function() {
// Close the connection, if open.
if (socket.readyState === WebSocket.OPEN) {
socket.close();
}
It is also possible to pass the code and reason parameters we mentioned earlier:
socket.close(1000, "Deliberate disconnection");
Integrative Programming and Technologies 101
Configuring the Server
• A server is nothing but a remote computer that has The following diagram shows WebSocket server and
specific hardware and software requirements in order to client event triggering:
achieve high availability and up-time, enhanced security,
and management of multiple concurrent connections.
• A WebSocket server is nothing but a simple program that
is able to handle WebSocket events and actions. It
usually exposes similar methods to the WebSocket client
API and most programming languages provide an
implementation. The following diagram illustrates the
communication process between a WebSocket server and
a WebSocket client, emphasizing the triggered events
and actions.
Integrative Programming and Technologies 101
Configuring the Server – Setting up the Server
Integrative Programming and Technologies 101
Configuring the Server – Setting up the Server
You can use this a guide for
developing your web socket in
JavaScript:
JavaScript: You can create a web server using
JavaScript thanks to Node.js.
Node.js (http://nodejs.org) is an event-driven
framework that lets you build real-time web
applications. It is also interpreted by Google's
JavaScript engine, V8.
Integrative Programming and Technologies 101
Configuring the Server – Setting up the development environment
Here is a list of some IDEs we
propose, along with the web
programming languages they
support:
Integrative Programming and Technologies 101
Configuring the Server – Connecting to the web server
Every WebSocket needs a valid host and After that, we can call the Start method
port.
and wait for the clients to connect.
When started, the server is able to accept
You can type any valid URL you’d like and incoming connections. The start method
specify a port that is not in use.
needs a parameter which indicates the
To represents the incoming connections socket that raised the events:
(clients) with the IWebSocketConnection
interface. We can create an empty list and
update it whenever someone connects or
disconnects from our service:
Integrative Programming and Technologies 101
Configuring the Server – Connecting to the web server
Open Close
The OnOpen event determines that a new client The OnClose event is raised whenever a client is
has requested access and performs the initial disconnected. We can remove that client from our list
and inform the rest of the clients about the
handshake. We should add the client to the list
disconnection:
and probably store any information related to it,
such as the IP address. It provides us with such
information, as well as a unique identifier for the
connection.
Integrative Programming and Technologies 101
Configuring the Server – Connecting to the web server
Message
The OnMessage event is raised when a client sends
data to the server. Inside this event handler, we can
transmit the incoming message to all of the clients, or
probably select only some of them. The process is
straightforward. Note that this handler takes a string
named message as a parameter:
Integrative Programming and Technologies 101
Configuring the Server – Connecting to the web server
Send
• The Send() method simply transmits the desired
message to the specified client. Using Send(), we
can deliver text or binary data across the clients.
Let's loop through the registered clients and
transfer the messages to them. We need to modify
the OnMessage event as follows:
Integrative Programming and Technologies 101
Data Transfer – Sending, Receiving and Decoding
The WebSocket protocol supports text and binary data. In JavaScript, text is
referred to as String, while binary data is represented by the ArrayBuffer and
Blob classes. Using plain text and binary format, you can transfer and
decode almost any type of HTML5 media.
Integrative Programming and Technologies 101
Data Transfer – Sending, Receiving and Decoding
String JSON
Whenever the onmessage event is raised, the client • JSON (JavaScript Object Notation) is a lightweight format
for transferring human-readable data between computers. It is
needs to check the data type and act accordingly. structured in key-value pairs, usually describing properties and
JavaScript can easily determine that a data type is of values. Due to its efficiency, JSON is the dominant format for
string type using the strict equal operator (that is, transferring data between server and client. Moreover, JSON is
===). a subset of JavaScript, so you can parse it immediately without
using external parsers!
Integrative Programming and Technologies 101
Data Transfer – Sending, Receiving and Decoding
JSON XML
Following code shows how you can handle a JSON You can parse XML-encoded strings
object and extract its properties:
using Javascript. You can use jQuery as
a method for your third party library.
Integrative Programming and Technologies 101
Data Transfer – Sending, Receiving and Decoding
ArrayBuffer Blobs
• ArrayBuffer contains structured binary data. The key term here is Blobs (Binary Large Objects) contain totally raw data in their most
structured, which means that the enclosed bits are given in an native form. A blob might theoretically be anything, even a non-
order, so that you can retrieve portions of them. In order to JavaScript object. As a result, interpreting blob data might be quite
manipulate an ArrayBuffer for specific formats, you need to
create the corresponding ArrayBufferView object. tricky. As a thumb rule, you'd better know exactly what the server is
supposed to send, otherwise you'll need to make fairly non-concrete
• ArrayBuffers are really handy for storing image files. Suppose assumptions.
that your chat-room guests can exchange images by dragging and
dropping image files on the chat window. Following code However, the big advantage of blob data is their file size. Binary
explains how JavaScript handles the drop event in HTML5
browsers: format is machine-level format, so there are almost no abstraction
layers used that would increase its size.
When you transmit multimedia over the web, you need the highest
speed possible, in order to achieve the best user experience. The
WebSocket blobs do not create extra burden for your Internet
connection and they rely on the client for proper interpretation.
Integrative Programming and Technologies 101
Data Transfer – Sending, Receiving and Decoding
Explanation:
Blobs • At first, you verify that the server message is an instance of blob, similar to the way you
checked for the buffered array. Then, you store the raw data to a local variable, named
Following code shows how you can display an blob.
incoming images, sent as a set of raw bits: • In order to display the blob in an image format, you need to decode it properly.
• The new JavaScript API makes basic image manipulation a piece of cake. Instead of
reading the bytes, you create a plain URL to the specified data source. This URL is alive as
long as the HTML document is alive. That means you cannot retrieve it after closing your
browser window.
• The window.URL property is currently supported in all the major browsers, though
Google Chrome has named it window.webkitURL. The createObjectURL
method generates a URL for the temporary file specified as a parameter. You do not
need to provide any further details or write any further code! JavaScript represents the
blob you received as a normal browser URL!
• Finally, using the DOM manipulation methods you already know, you create an image
element, you provide it with the new URL, and you insert it right at the end of the HTML
document.
Integrative Programming and Technologies 101
Error Handling
• When it comes to error handling, you have to take both
Similarly, HTML has XMLHttpRequest for determining
internal and external parameters into account. Internal
parameters include errors that can be generated because network availability. HTML5, though, made it even easier and
of the bugs in your code, or an unexpected user behavior.
External errors have nothing to do with the application; introduced a way to check whether the browser can accept web
rather, they are related to parameters you have no control responses. This is achieved via the navigator object:
on. The most important one is the network connectivity.
Any interactive bidirectional web application requires,
well, an active Internet connection.
• Checking Network Availability: Imagine that your users
are enjoying your web app, when suddenly the network
connection becomes unresponsive in the middle of their
task. In modern native desktop and mobile applications, it
is a common task to check for network availability. The
most common way of doing so is simply making an
HTTP request to a website that is supposed to be up (for
example, http://www.google.com). If the request
succeeds, the desktop or mobile device knows there is
active connectivity.
Integrative Programming and Technologies 101
Error Handling
• Offline mode means that The preceding code is pretty simple. It checks the error code to
either the device is not determine whether the WebSocket connection was closed
connected or the user has successfully. Error code 1000 would determine exactly this. If
selected the offline mode the close event was raised due to an error, the code would not be
from his/her browser toolbar. 1000. In this case, the code checks for connectivity and informs
the user appropriately.
• Here is how to inform the
user that the network is not
available and try to reconnect
when a WebSocket close
event occurs:
Integrative Programming and Technologies 101
Error Handling - Fallbacks
• Here come the fallback solutions, which can handle such situations and provide a gracefully scaled-down
experience to the users of older browsers. There are two kinds of popular fallbacks nowadays, Plugins (such as
Flash or Silverlight) and JavaScript hacks, formally known as polyfills.
JavaScript Polyfills
• We start by examining polyfills, as they are more close to the native web. JavaScript polyfills are solutions and
libraries that mimic a future feature, by providing support for older browsers. Currently, there are polyfill solutions
for almost all HTML5- specific feature (canvas, storage, geolocation, WebSockets, CSS3, and so on). A polyfill
solution should be used in parallel to the standards-based, HTML5- compliant API.
• If you need to implement both an HTML5 and a polyfill solution, why not just implement the second one and save
time and money? Well, here are four reasons you should use both:
1. Better user experience: When using HTML5, you serve your visitors the best and smoothest experience possible.
Everything is handled by the browser, and you only need to focus on your application's requirements. When usinga
polyfill to address a specific issue, the end-product cannot be of the same quality. Surely, delivering something is better
than delivering nothing, but a polyfill is just a patch for those who run poorer vehicles.
Integrative Programming and Technologies 101
Error Handling - Fallbacks
2. Performance: The most significant advantage between a native HTML5 solution and a polyfill plugin, is
performance. When you request a JavaScriptfile, you require extra resources, which increase loading time. Moreover, a
JavaScript plugin runs way slower than a native browser-implemented method. Regarding WebSockets, the protocol is
designed to provide bidirectional full-duplex communication. That is the fastest way you can achieve this kind of staff.
What a polyfill can do is to simply mimic fullduplex communication, using traditional AJAX polling. We have already
seen that AJAX polling is way slower than WebSockets.
3. Future-friendly: Using HTML5 right now lets your website or app to be automatically enhanced from any future
browser update. For example, someone who used canvas three years ago, benefitted automatically when Internet
Explorer was updated to Version 9.
4. Standards-friendly: Although content, not web standards, should be our top priority, it is good to know that our
current implementation consorts with the formal technical specifications. Moreover, the web standards propose what is
known as "best practices". Although polyfills usually consist of valid JavaScript code, most of the time they need to
address browser-
Integrative Programming and Technologies 101
Error Handling - Fallbacks
Popular PolyFills
• Modernizr, a well-
known library for
detecting HTML5 and
CSS3 features, provides
a great list of HTML5
polyfills that can make
your life much easier
when it comes to
supporting older
browsers.
Integrative Programming and Technologies 101
Error Handling - Fallbacks
Browser Plugins
• Browser plugins have been an extremely helpful solution for rich Internet applications in the pre-HTML5 era. To
name but a few, developers used to offer desktop-rich functionality in their websites utilizing the capabilities of
Flash (primarily), Silverlight, or Java. A few years ago, basic UX effects, transitions, and animations could not be
made using plain HTML, CSS, or JavaScript.
• To fill this gap, browser plugins provided the developers with a framework which could be installed in the client
browser and allowed richer content.
• Browser plugins have several drawbacks that make them deprecated day-by-day. They are resource-intensive, the
user needs to wait more until a page is fully loaded, and they are mostly based on proprietary technologies. As a
result, more and more companies (including Apple and Microsoft) are shifting away from browser plugins in favor
of HTML5.
• Websocket-as, is a popular utility, written in ActionScript, which implements a WebSocket API like the HTML5
approach.
Integrative Programming and Technologies 101
Summary
• In this chapter, we built our first WebSocket client application! We introduced the WebSocket object and explained its various
methods, events, and properties. We also developed a basic chat client in a few lines of HTML and JavaScript code. As you noticed
in the current examples, there is only a dummy server which echoes the messages. Read on to find out how we you can configure
your own WebSocket server to do a lot more magic.
• The WebSocket API, illustrated how to configure a client using JavaScript and this chapter showed you how you can configure a
WebSocket server using the environment and programming language you are most familiar with. Moreover, we had a look at the
WebSocket server events and actions.
• You had a detailed look at the various data formats the WebSocket protocol supports. You implemented various examples using
string and binary data (text, images, and videos), found out how you can properly encode and decode the client-side data, and
finally extended the chat demo to manipulate images and videos. The next chapter discusses security considerations over the web
that will make your apps even more robust.
• Not all browsers support the WebSocket protocol natively. As a result, you need to provide some fallback solutions for those users
who cannot sense the HTML5 goodies. Fortunately, the open-source community has provided us with various techniques, which
emulate the WebSockets' features using plain HTTP or Flash internally. Implementing both the HTML5 and the fallback is critical
for your web apps and is strongly related to the audience width you want to reach. In this chapter, we examined some popular
fallback techniques and saw how to handle common connectivity errors in your WebSocket applications. That's all you need to
know for the WebSocket and HTML part.
Integrative Programming and Technologies 101
Thank You!