Getting Connected With HTML5 Web Sockets


The Web Socket specification defines an API establishing "socket" connections between a web browser and a server. There is a persistent connection between the client and the server and both parties can start sending data at any time.

In the  demo we have a small application titled Web Sockets, that when connected (press the Connect button), can send messages to the test sever at echo.websocket.org. It simply echo’s back what you typed in. Read the code in scripts/webSockets.js as it is fairly self-explanatory.

You open up a Web Socket connection simply by calling the Web Socket constructor:

var _ws = new WebSocket( "ws://echo.websocket.org" );

Notice the ws:. This is the new URL schema for Web Socket connections. There is also wss: for secure Web Socket connection the same way https: is used for secure HTTP connections.

Attaching some event handlers immediately to the connection allows you to know when the connection is opened, received incoming messages, or there is an error.

The second argument accepts optional sub protocols. It can be a string or an array of strings. Each string should represent a sub protocol name and server accepts only one of passed sub protocols in the array. Accepted sub protocol can be determined by accessing protocol property of Web Socket object.

The sub protocol names must be one of registered sub protocol names in IANA registry. There is currently only one sub protocol name (soap) registered as of February 2012.

// When the connection is open, send some data to the server
connection.onopen = function () {
     connection.send('Ping'); // Send the message 'Ping' to the server
};

// Log errors
connection.onerror = function (error) {
     console.log('WebSocket Error ' + error);
};

// Log messages from the server
connection.onmessage = function (e) {
     console.log('Server: ' + e.data);
};

As soon as we have a connection to the server (when the open event is fired) we can start sending data to the server using the send('your message') method on the connection object. It used to support only strings, but in the latest spec it now can send binary messages too. To send binary data, you can use either Blob or ArrayBuffer object.

// Sending String
connection.send('your message');

// Sending canvas ImageData as ArrayBuffer
var img = canvas_context.getImageData(0, 0, 400, 320);
var binary = new Uint8Array(img.data.length);

for (var i = 0; i < img.data.length;  i++) {
     binary[i] = img.data[i];
}
connection.send(binary.buffer);

// Sending file as Blob
var file = document.querySelector( 'input[type="file"]' ).files[0];
connection.send(file);

Equally the server might send us messages at any time. Whenever this happens the onmessage callback fires. The callback receives an event object and the actual message is accessible via the data property.

Web Sockets can also receive binary messages in the latest spec. Binary frames can be received in Blob or ArrayBuffer format. To specify the format of the received binary, set the binaryType property of Web Socket object to either 'blob' or 'arraybuffer'. The default format is 'blob'. (You do not have to align binaryType parameter on sending.)

// Setting binaryType to accept received binary as either 'blob' or 'arraybuffer'
connection.binaryType = 'arraybuffer';

connection.onmessage = function(e) {
     console.log(e.data.byteLength); // ArrayBuffer object if binary
};

Fallback Solution

Obviously many browsers do not support Web Sockets, but it is fairly easy to implement a Flash Socket fallback, the best one probably being:


All you need to do is include this library into your website, according to its instructions, and make sure the server has a Flash Policy file served on the correct port. The only other change that would be needed to webSockets.js, would be to give the location of the .swf for the Flash Socket:

WEB_SOCKET_SWF_LOCATION = “scripts/WebSocketMainInsecure.swf”

You can then write JavaScript code for Web Sockets in the normal manner.



Published on 4 April 2014 in HTML5 Features