Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Working with WebSockets in HTML5

In this article we will work with the concept of websockets, which is a new addition to the HTML5 specification, this, in turn, allows a web server to connect to the browser and communicate directly with him.

Working with WebSockets?

WebSockets are designed to provide a persistent connection between a client and a server where both parties can be used to start sending data at any time. In this way, the client establishes a WebSocket connection through a process in which the client sends an HTTP request to the regular server, with it, an upgrade header goes included in this request that tells the server that the client intends to establish a connection via WebSocket. An example header that can be sent is displayed as follows:

GET ws://example.websocket.com/ HTTP/1.1
Origin: http://example.com 
Connection: Upgrade 
Host: example.websocket.com 
Upgrade: websockets

As we can see, the URL of the WebSocket uses the ws scheme, where in addition to this, we can still use the WSS that is to secure WebSocket connections. Also, this connection is equivalent to HTTPS. If the server has supported the use of WebSockets protocol, it agrees with the update and returns a new header update in its response, as we can see below:

HTTP 101 WebSocket Protocol Handshake  Date: Wed, 16 Feb 2015 22:07:34 GMT 
Connection: Upgrade 
Upgrade: WebSocket

With the communication completed, the initial HTTP is replaced by a Websocket connection using the same connection TCP/IP underlying, as of this moment, any party may start sending data. With Websockets, data transfer can be made without the occurrence of overloads associated to the HTTP requests, therefore, the data is transferred through a Websocket as a message, consisting of one or more frames that owns the data that are being sent. In order for the message to be reconstructed in an appropriate manner, to arrive at the client, each of the frames is pre-set with a size of 4 to 12 bytes of data payload. Using this system frames based messages there is a significant reduction in latency and the amount of data that would be sent in a single packet. It is important to note here that the client will only be notified of the new message since all the frames have been received and the original message payload has been rebuilt.

In order to understand better about the concept of Websockets, nothing better than learning performing the development of a simple example for that, from now on we will present some of the most important items and the common use of Websocket in HTML5.

Creating a simple example of WebSockets

To start with our example, first we choose the IDE that we more adapt ourselves to the construction of our code at this time, so we will use Netbeans, but feel free to develop the way they see fit. That said, first we create our index.html page, according to the presented by Listing 1.

Listing 1. Creating the index.html page.

<!DOCTYPE html>
<html>
  <head>
	  <title>WebSockets with HTML5</title>
	  <meta charset="UTF-8">
	  <meta name="viewport" content="width=device-width, initial-scale=1.0">
	  <link rel="stylesheet" href="style.css">
  </head>
  <body>
	  <div id="page-wrapper">
		  <h1>Example of WebSockets use</h1>


		  <div id="status">Conecting to the application...</div>


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


		  <form id="form-message" action="#" method="post">
			  <textarea id="message" placeholder="Wirte your message here!" required></textarea>
			  <button type="submit">Send Message</button>
			  <button type="button" id="close">Close connection</button>
		  </form>
	  </div>
	  <script src="app.js"></script>
  </body>
</html>

At this time, we have created some key elements that will be used by our application, among which, here we have a <div> responsible for the display of messages on the connection status; beyond, we have a list that will be used to present the messages sent and received from the server; and also, we will have a form for inserting messages that are sent. Now that we have our index.html page created, we realize that we will also have to create a CSS file, we call style and a js file, we call app.js, which are presented according to Listings 2 and 3.

Listing 2. Creating style file style.css.

*,
*:before,
*:after {
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}
html {
    font-family: Helvetica, Arial, sans-serif;
    font-size: 100%;
    background: #333;
}
#page-wrapper {
    width: 650px;
    background: #FFF;
    padding: 1em;
    margin: 1em auto;
    border-top: 5px solid #69c773;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.8);
}
h1 {
    margin-top: 0;
}
#status {
    font-size: 0.9rem;
    margin-bottom: 1rem;
}
.open {
    color: green;
}
.closed {
    color: red;
}
ul {
    list-style: none;
    margin: 0;
    padding: 0;
    font-size: 0.95rem;
}
ul li {
    padding: 0.5rem 0.75rem;
    border-bottom: 1px solid #EEE;
}
ul li:first-child {
    border-top: 1px solid #EEE;
}
ul li span {
    display: inline-block;
    width: 90px;
    font-weight: bold;
    color: #999;
    font-size: 0.7rem;
    text-transform: uppercase;
    letter-spacing: 1px;
}
.send {
    background-color: #F7F7F7;
}
.received {} #form-message {
    margin-top: 1.5rem;
}
textarea {
    width: 100%;
    padding: 0.5rem;
    font-size: 1rem;
    border: 1px solid #D9D9D9;
    border-radius: 3px;
    box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.1);
    min-height: 100px;
    margin-bottom: 1rem;
}
button {
    display: inline-block;
    border-radius: 3px;
    border: none;
    font-size: 0.9rem;
    padding: 0.6rem 1em;
    color: white;
    margin: 0 0.25rem;
    text-align: center;
    background: #BABABA;
    border-bottom: 1px solid #999;
}
button[type="submit"] {
    background: #86b32d;
    border-bottom: 1px solid #5d7d1f;
}
button:hover {
    opacity: 0.75;
    cursor: pointer;
}

Now that we have our style class created where we only define some items for a better view of our example project, we will go to the creation of our JavaScript file, as shown by Listing 3.

Listing 3. Creation of the app.js file.

window.onload = function() {
	//  Get all references to the page elements
	var form = document.getElementById('form-message');
	var txtMsg = document.getElementById('message');
	var msgList = document.getElementById('messages');
	var socketStatus = document.getElementById('status');
	var btnClose = document.getElementById('close');
};

As shown, we create here a number of variables and initialize them for the search of the key elements on the page. Thus, we have the beginning of our application, where we have a demo application configured and so we can start learning about the WebSocket API. At first, we see here how we can make a connection through the WebSocket. To create a connection there will be no difficulty, where all we need to do is call the WebSocket constructor and pass the URL of the server that will be used, as we see from the following code which we will include in our app.js file, as shown by Listing 4.

Listing 4. Opening a connection with WebSockets.

// Creating a new connection
var socket = new WebSocket('ws://echo.websocket.org');

The website echo.websocket.org is adefacto test bed for websocket-based applications and services. We will use it as the server side to build our examples.Once we have established the connection, the open() event fires to our WebSocket instance. In our application, what we are doing is to add an event listener that will update the status of the <div> with a message, showing that the connection is established. Now that we have our connection, we will add this code snippet in our app.js file, as shown in Listing 5.

Listing 5. Showing an WebSocket opening message.

socket.onopen = function(event) { 
	socketStatus.innerHTML = 'Connected!';
	socketStatus.className = 'open';
};

With WebSockets we can also retrieve errors that may occur during a Listener that starts an error event. In our case, for simplicity, we are only presenting these errors in a console through the code presented in accordance with the Listing 6. The result of this implementation can be seen in Figure 1.

Listing 6. Code regarding errors.

socket.onerror = function(error) { 
	console.log('WebSocket error: ' + error); 
};

Figure 1. Result of connection test.

Now that we have seen how we can make a connection and capture errors, what else could we have with websockets? What we lack at the moment is sending the messages, which, to be sent over the WebSocket connection, we call the send() method in our WebSocket instance, where we will send the data to be transferred, which we present as follows:

socket.send(data)

With Websockets, we can send both text and binary data. In our example, we will send the contents of the field to the server when the form is submitted. So we can do this, we must first have a Listener event set in the form, which we will do according to Listing 7.

Listing 7. Sending the form data.

form.onsubmit = function(e) {
		e.preventDefault();
	   
		// Recovering the textarea message.
		var message = txtMsg.value;
	   
		// Sending the message through the WebSocket.
		socket.send(message);
	   
		// Adding the message in a sent list.
		msgList.innerHTML += '<li class="envia"><span>Sent:</span>' + message + '</li>';
	   
		// Cleaning the field with the message after the sending.
		txtMsg.value = '';
	   
		return false;
  };

When the form is submitted, the code presented by Listing 7 aims to regain the message of the field txtMsg and then send it through the WebSocket. The message is then added to the mailing list called msgList and displayed on the page. You can see the final result in Figure 2.

Figure 2. Final result of the test.

Conclusion

With this we finish our article about using WebSockets, where we saw that it aims to set a persistent bi-directional communication between web servers and clients, which means that both parties can exchange messages data at the same time. They are optimized for high performance and results in more responsive and rich web applications.



Web developer and passioned for web design, SEO and front end technologies.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login