WebSocket API
The traditional browser/server request and response methodology over the HTTP protocol incurs the use of heavy headers for each client-initiated request (pull). This renders the protocol inefficient for the needs of hyper-interactive real-time applications like live video streaming, browser-based games, chats, etc.
HTML5's WebSocket protocol gives provision for such persistent real-time bi-directional TCP connection between a client (browser) and a server, without the need/use of AJAX methodology or 'Long Polling', doing away with headers thereby decreasing network load and improving performance. You can think of WebSocket as a full-duplex messaging system, akin to land-line telephones, where users at both ends can speak and hear simultaneously.

ws://
and wss://
are the two WebSocket URI schemes for normal (unencrypted) and secure (encrypted) connections, analogous to http://
and https://
connections. When the HTTP protocol switches to WebSocket, it is known as a "handshake".
WebSocket was initially hinted as TCP connections in the HTML5 specification. The term WebSocket
was coined during a chat session led by Ian Hickson ("Hixie") at #whatwg IRC chat room way back in June, 2008.

To open a WebSocket connection, the WebSocket constructor needs to be called, passing the necessary arguments.
var ws = new WebSocket("ws://somehost:8080/", "protocolA");
The first parameter is the URL to connect to (with either the ws://
or wss://
scheme) and is required. The second parameter is either a string specifying a sub-protocol or an array of sub-protocols, and is optional. If sub-protocols are passed, the server should support at least one of it. The WebSocket object's protocol
property will give you the protocol the server selected
ws.protocol;
Several events are associated during the lifetime of a WebSocket connection, and the useful ones are outlined below
open
readyState
attribute assumes the value 1 (OPEN)
.
message
message
event is triggered when a message is received from the server.
error
close
readyState
attribute changes its value to CLOSED
(3)
.
A simple code which connects automatically to a WebSocket server, sends some message, displays the response from the server, and closes the connection is wrapped inside a self-invoking function below. We make use of KAAZING's WebSocket server called "echo server" hosted on https://www.websocket.org/echo.html, which echoes back messages sent from the client. The ("WebSocket" in window)
condition detects the browser's support for WebSocket
(function() {
if ("WebSocket" in window) {
console.log("Your browser supports WebSocket.");
var ws = new WebSocket("ws://echo.websocket.org/");
ws.addEventListener('open', function(e) {
ws.send("Help me, Obi-Wan Kenobi. You're my only hope. - Princess Leia");
console.log("Message is sent to Obi-Wan Kenobi.");
});
ws.addEventListener('message', function(e) {
console.log("Obi-Wan Kenobi echoed back: ", e.data);
ws.close();
});
ws.addEventListener('error', function(err) {
console.log('WebSocket Error: ', err);
});
ws.addEventListener('close', function(e) {
console.log("WebSocket connection closed.");
});
}
else {
console.log("Your browser does not support WebSocket.");
}
})();

Alternatively, instead of addEventListener()
, we can use the corresponding event handlers onopen
, onmessage
, onerror
and onclose
as shown below
(function() {
if ("WebSocket" in window) {
console.log("Your browser supports WebSocket.");
var ws = new WebSocket("ws://echo.websocket.org/");
ws.onopen = function(e) {
ws.send("Help me, Obi-Wan Kenobi. You're my only hope. - Princess Leia");
console.log("Message is sent to Obi-Wan Kenobi.");
};
ws.onmessage = function(e) {
console.log("Obi-Wan Kenobi echoed back: ", e.data);
ws.close();
};
ws.onerror = function(err) {
console.log('WebSocket Error: ', err);
};
ws.onclose = function(e) {
console.log("WebSocket connection closed.");
};
}
else {
console.log("Your browser does not support WebSocket.");
}
})();

To confirm the various constants used by the readyState
attribute, just console.log()
the e.currentTarget.readyState
property inside the event handlers of corresponding events. An example is given below
ws.onopen = function(e) {
ws.send("Help me, Obi-Wan Kenobi. You're my only hope. - Princess Leia");
console.log("Message is sent to Obi-Wan Kenobi.");
console.log("readyState: ", e.currentTarget.readyState);
};
You can try KAAZING's "Echo Test", sending out your own custom messages at https://www.websocket.org/echo.html

There also exists several browser extensions for Chrome like Web-Socket Client
, Smart Websocket Client
and Simple WebSocket Client
for debugging/testing a WebSocket connection between a client and a server.
