Develop bidirectional browser-server Sites with HTML5 WebSocket API


Develop bidirectional browser-server Sites with HTML5 WebSocket API

Recipe ID: hsts-r64


Self-paced training

We offer HTML5, CSS3, JavaScript,Bootstrap, Angular.JS, WordPress Node.JS, React.JS, Joomla, Drupal, Vue.JS and more classes in self-paced video format starting at $60. Click here to learn more and register. For complete self-paced web design training, visit our Web design and development bundle page.


In this tutorial, our goal is to create persistent, two-way communication between a web application and the server, so that both the browser and the server can send and receive data to and from each other as needed.

Web Socket API Overview

The WebSocket API is an advanced technology that makes it possible to open a two-way interactive communication session between the user's browser and a server. With this API, you can send messages to a server and receive event-driven responses without having to poll the server for a reply.

Step-by-step Implementation

Most browsers now have the native ability to establish a bidirectional socket connection between themselves and the server, using the WebSocket API. This means that both sides (browser and server) can send and receive data. Common use cases for Web Sockets are live online games, stock tickers, chat clients, etc.

To test if the browser supports Web Sockets, use the following feature-detect for the
WebSocket API:
var websockets_support = !!window.WebSocket;
Now, let’s build a simple application with chat room–type functionality, where a user may read the current list of messages and add her own message to the room.
We will have a text entry box where new messages are written before being sent, and we will have a list of messages in the chat room. We do not need features such as login or authentication here, only simple chat room message sending and receiving:
<!DOCTYPE html>
<html>
<head>
<title>Our Chatroom</title>
<script src="chatroom.js"></script>
</head>
<body>
<h1>Our Chatroom</h1>

<div id="chatlog"></div>

<input id="newmsg" /><br />
<input type="button" value="Send Message" id="sendmsg" />
</body>
</html>

Now, let’s examine the JavaScript in chatroom.js:

var chatcomm = new WebSocket("ws://something.com/server/chat");

chatcomm.onmessage = function(msg) {
msg = JSON.parse(msg); // decode JSON into object

var chatlog =  document.getElementById("chatlog"); var docfrag = document.createDocumentFragment(); var msgdiv;

for (var i=0; i<msg.messages.length; i++) { msgdiv = document.createElement("div");
msgdiv.appendChild(document.createTextNode(msg.messages[i])); docfrag.appendChild(msgdiv);
}

chatlog.appendChild(docfrag);
};

chatcomm.onclose = function() {
alert("The chatroom connection was lost. Refresh page to reconnect.");
};

document.getElementById("sendmsg").addEventListener("click",     function(){ var newmsg = document.getElementById("newmsg");

chatcomm.send(newmsg.value); // send the message to the server

newmsg.value = ""; // clear out the message entry box
},false);

Let’s break down that code just a little bit. First we create the socket and point it at a location on our server. The server URL in our example uses the “ws://” protocol, as opposed to the more common “http://” you’re familiar with. This signals the special protocol that Web Sockets use between client and server.
Next, we set up two event listeners on our socket object: onmessage and onclose. The
onclose handler is self-explanatory—it is fired when the connection is closed.

Our onmessage handler receives a string of data (which in our example we expect to be JSON) and parses it into a message object. The message object contains an array of one or more messages (each one is just simple text). The handler loops through each message, adding it to the chat log in the order received.
Lastly, the code sets up a click event handler on the “Send Message” button. When clicked, the handler takes whatever has been typed into the text entry input and sends it to the server, using the send(...) method.

Summary

Admittedly, this type of functionality is not at all new. Since the advent of Ajax, using the XMLHttpRequest (“XHR”) object, developers have been sending and receiving data between browser and server. Other approaches have included instantiating an invisible Flash object and using Flash’s socket communication capabilities.
However, it’s quite inefficient in the XHR approach to establish a whole new connection for each piece of data you need to send from browser to server. It’s similarly undesirable to instantiate a memory-heavy Flash instance to use socket communication. So, Web Sockets are understandably a welcomed addition to the “HTML5 & Friends” family of technologies.
The message sending and receiving in Web Sockets is like a sensible mix between XHR and Web Workers, which we looked at in the previous recipe.

The WebSocket object instance has, similar to XHR, a readyState property that lets you examine the state of the connection. It can have the following constant values:
{worker}.CONNECTING (numeric value 0)
Connection has not yet been established
{worker}.OPEN (numeric value 1)
Connection is open and communication is possible
{worker}.CLOSING (numeric value 2)
Connection is being closed
{worker}.CLOSED (numeric value 3)
Connection is closed (or was never opened successfully)

 

The events that a WebSocket object instance fires are:

For each of these events, you can add an event listener using addEventListener(...),  or you can set a corresponding handler directly on the worker object instance, including onopen, onmessage, onerror, and onclose.
If Web Sockets are not supported, you will need to provide some fallback functionality for your application, or at least gracefully notify the user that his browser does not support the required functionality. Fortunately, there is a very easy way to do that.
Because consistent browser support for Web Sockets has been elusive, the best practice suggestion for using Web Sockets is to use a library like Socket.io which attempts to use Web Sockets if available, and falls back to a variety of other techniques for communication if Web Sockets are not present.

You should also be aware of how Web Sockets usage scales in terms of server resources. Traditional web requests only take up dedicated resources from the server for a split second at a time, which means you can serve a lot of web traffic from your server without having too much overlap and thus running out of resources.
Sockets, on the other hand, tend to be more dedicated, so there can be issues with resource availability under high load. Your server setup and architecture will vary greatly with your application’s needs and are a big factor in how well you are able to utilize Web Sockets.

 

Here is the list of other related tutorials that are highly recommended:



Here is the list of classes that are highly recommended:

 

Click here if you wish to learn more about training and career options available in the IT industry.


Private and Custom Coding Classes

We offer private coding classes for beginners online and offline (at our Virginia site) with custom curriculum for most of our classes for $59 per hour online or $95 per hour in virginia. Give us a call or submit our Private Coding Classes for Beginners form to discuss your needs.


View Other Classes!