WebSockets: how it works and how to use it

How it works?

Websockets is a web technology, which allows bi-directional, real-time communications between web client and a server. As part of the HTML5 specification it works with the newest web browsers (including Internet Explorer 10 and its latest versions).

Every connection begins as HTTP to provide full support for legacy solutions. Web client sends a request to the server and, if the server supports the WebSockets protocol, it sends a response, in which it overwrites the connection header. Since this moment a WebSockets-based connection is made.

WebSockets fast as lightning

According to some studies WebSockets protocol is three times faster than HTTP, what means the improvement of the speed of data exchange between applications. One of the biggest advantages of using WebSockets is that it doesn't interfere with firewalls and proxy servers, which was the bane of the most solutions.

The most common examples of the WebSockets protocol usage are real-time applications such as IM, collecting and analysing data, ducuments cooperation or browser games.

Socket.IO and WebSockets

Socket.IO is a JavaScript library that helps improving work with WebSockets. It consists of two parts – server part (for Node.JS) and clients part (for web browsers). Both of them have similiar APIs based on event-driven architecture. Socket.IO allows to use additional features such as sending data to large number of sockets at the same time (broadcasting) or storing the data.

The main idea behind Socket.IO is the ability to send and receive any events with any data. It can be any object as well as a binary data.

Socket.IO in practice – the chat ( based on examplefrom the official website of Socket.io)

The easiest way to explain how Socket.IO works is to illustrate it with the example. By writing just 22 lines of JavaScript code, we can create a simple WebSockets-based chat. Below you will find both the server and the client part with explanatory comments.
Server part uses Node.JS, therefore at first we have to install it on the computer. To install necessary packages we need the node package manager (nmp), which we will recieve during the installation.

Let's start with the Express installation. Express is a Node.JS framework that helps in making the work as easy as possible. To install it, type the command:

npm install express –save-dev

For our work we also need the Socket.IO library. Install its server part by typing the command:

npm install socket.io –save-dev

While installing dependences by using nmp with –save-dev flag we are also adding them to the package.json.

// Use Express framework, which allows us to support HTTP protocol and Socket.IO
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

// Define the route and select the file - in this case it is index.html
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});

// Listen 'connection' event, which is automatically send by the web client (no need to define it)
io.on('connection', function(socket){
// Listen 'chat message' event, which is sent by the web client while sending request
socket.on('chat message', function(msg) {
// Emit event to all connected users. The second parameter should be the content of the message
io.emit('chat message', msg);
});
});

// Select the port to be listened by the server
http.listen(3000, function() {
console.log('Listening on *:3000');
});

Since we have installed Express and Socket.IO, we are ready to write the server part of the application. Below you can find the JavaScript code with comments that explain individual parts of the code.

<!doctype html>
<html>
<head>
<title>Socket.IO Chat</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; }
form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
</style>
</head>
<body>
<!-- The list of messages returned by Node.js server -->
<ul id="messages"></ul>

<!-- The form, which will be used to send messages -->
<form action="">
<input id="message" autocomplete="off" />
<button>Send</button>
</form>

<!-- Add Socket.IO and jQuery -->
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
// Create variable to which we ascribe Socket.IO mechanism
var socket = io();

// While submitting this form we also send 'chat message' event to the Node.JS server. The second parameter is a message entered in the file with 'message' id
$('form').submit(function(){
socket.emit('chat message', $('#message').val());
$('#message').val('');
return false;
});

// Listen 'chat message' event sent by Node.JS server. We will receive the content of this message as a parameter. Then assign it to the list of 'messages' id
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
</script>
</body>
</html>

When both parts (server and client) are ready, we can launch the Node.JS server. To do this type the command:

node server.js

Now go to this page and open it in two different bookmarks. While typing the message in one of them and sending it to the server, the text should display in both bookmarks. This is how you create the chat that works in real-time by using just 22 lines of JavaScript code. That's the magic of WebSockets and this is just the beginning – the possibilities are endless.

Merixstudio uses WebSockets

Are you wondering how to connect classic „Snake” game with WebSockets, the technology that ensures bi-directional communication? Be sure to check out our game, which is the perfect example of the WebSocket's possibilities!

Conclusion

WebSockets is one of the most interesting conveniences that was brought into the use with HTML5. It solves a lot of problems that web application developers have struggled with before. WebSockets in combination with external libraries such as Socket.IO gives many possibilities.This definitely is a noteworthy technology.

Navigate the changing IT landscape

Some highlighted content that we want to draw attention to to link to our other resources. It usually contains a link .