HTML5 WebSocket API

HTML5 WebSocket API with Examples: The HTML5 WebSocket protocol is used for two way communication which defines API with a remote host. It has a WebSocket interface that defines a full-duplex communication channel to operate through a single socket for entire the web.

In full-duplex communication which is maintained by the two connections, the HTML5 WebSocket specifies the reduction for unnecessary network traffic and un-scalable polling and long polling solutions.

The HTML 5 WebSockets which are used for network hazards like proxies and firewall, that is making the connection for streaming which supports upstream and downstream in a single connection. These HTML 5 WebSocket applications are less burden on servers because it allows existing machines for more concurrent connections.

HTML5 WebSocket API

 

HTML5 WebSocket Architecture

HTML5 WebSocket has a unique feature that defines the ability to traverse proxies and firewalls, these are the problems for many applications. The comet-style applications which occupy long polling as the rudimentary line of defense are used against the firewalls and proxies.

This technique is good but not suited for applications like sub-500ms latency or requires high throughput. The Adobe Flash which is plugin-based technology has some level of socket support but it has been a burden to proxy and firewall traversal problems which WebSocket resolve.

HTML5 WebSocket automatically detects the proxy server and sets a tunnel to pass the proxy. This tunnel establishes by issuing an HTTP CONNECT statement to a proxy server that opens TCP/IP connection for required host and port. Once the tunnel is created and communication can happen through the proxy.

However, the HTTP’s works similarly to the WebSocket over SSL can hold the same HTTP connect technique. The WebSocket is supported by modern browsers where backward-compatible implementations are taking advantage of this emerging technology.

The Local Storage and Geolocation are part of HTML5 but later moved as standard documents. These WebSockets are caved in Internet Engineering Task Force (IETF) by its creators, the Web Hypertext Application Technology Working Group (WHATWG).

The HTML5 WebSocket Protocol

This WebSocket protocol was used to work with existing Web infrastructure. The protocol defines WebSocket connection starts as HTTP connection and providing complete backward compatibility with the pre-WebSocket world. The WebSocket handshake is the protocol switch from HTTP to WebSocket.

Here the browser sends a request to the server for switching protocols from HTTP to WebSocket and the client specifies its desires through upgrade header:

HTML5 WebSocket Protocol Example

GET ws://echo.websocket.org/?encoding=text HTTP/1.1
Origin: http://websocket.org
Cookie: __utma=99as
Connection: Upgrade
Host: echo.websocket.org
Sec-WebSocket-Key: uRovscZjNol/umbTt5uKmw==
Upgrade: WebSocket
Sec-WebSocket-Version: 13
If the server understands the WebSocket protocol, it agrees to the protocol switch through the Upgrade header.
HTTP/1.1 101 WebSocket Protocol Handshake
Date: Fri, 10 Feb 2012 17:38:18 GMT
Connection: Upgrade
Server: Kaazing Gateway
Upgrade: WebSocket
Access-Control-Allow-Origin: http://websocket.org
Access-Control-Allow-Credentials: true
Sec-WebSocket-Accept: rLHCkw/SKsO9GAH/ZSFhBATDKrU=
Access-Control-Allow-Headers: content-type

Here the HTTP connection stops and it is replaced by the WebSocket connection with the same TCP/IP connection. The default ports that WebSocket uses are HTTP (80) and HTTPS (443)

Using the HTML5 WebSocket API

With the help of one succinct interface(see the below list) developers can replace these techniques like long polling and forever frames which reduces latency.

HTML5 WebSocket API Example

[Constructor(in DOMString url, optional in DOMString protocol)]
interface WebSocket {
readonly attribute DOMString URL;
// ready state
const unsigned short CONNECTING = 0;
const unsigned short OPEN = 1;
const unsigned short CLOSED = 2;
readonly attribute unsigned short readyState;
readonly attribute unsigned long bufferedAmount;
// networking
attribute Function onopen;
attribute Function onmessage;
attribute Function onclose;
boolean send(in DOMString data);
void close();
};
WebSocket implements EventTarget;

To use WebSocket interface it may not be simple. To connect endpoint, by creating a new WebSocket instance with a new object contains URL which you want to connect as shown in example ws:// and wss:// and these prefix are used to indicate a WebSocket and secure connection.

New Web Socket Example

var myWebSocket = new WebSocket("ws://www.websockets.org");

The WebSocket connection established by upgrading the Http protocol to the WebSocket protocol during the first handshake between client and server. The connection provides “onmessage” and “send” functions by the WebSocket interface.

To get a series of event listeners to handle each phase of the connection life cycle have to follow the mentioned example.

To get a series of Event Listeners Example

myWebSocket.onopen = function(evt) { alert("Connection open ..."); };
myWebSocket.onmessage = function(evt) { alert( "Received Message: " + evt.data); };
myWebSocket.onclose = function(evt) { alert("Connection closed."); };

In case you may want to send a message to a server, simply by calling “send” and specify the data you want to deliver. after completion of sending the message, you have called “close” to terminate the connection, which is shown in the below example and it the easiest way.

Example to Terminate the Connection 

myWebSocket.send("Hello WebSockets!");
myWebSocket.close();