HTML and CSS Reference
In-Depth Information
The complexity of the HTTP handshake is largely irrelevant from the programmers point
of view. The following code will establish a Web Socket connection:
var connection = new WebSocket('ws://localhost/tasklist', ['json']);
Notice that the URL is not prefixed with HTTP:
This could also be set to “wss” in order to use a secure connection.
The second parameter contains a list of sub-protocols (or data formats) that the client ac-
cepts. This is used to ensure the client and the server are speaking the same language on
top of the Web Socket protocol. For instance, some applications may wish to use JSON
data formats, while others will use XML, while the server may support both data formats.
If multiple sub-protocols are specified, the server can determine the preferred protocol. It
is even possible to utilize a custom protocol specific to the application you are writing.
It is possible to attach a callback to the connection to hear that the connection has been
connection.onopen = function () {
console.log('The connection is open');
If the client specified that it accepted multiple protocols, it can also determine which one
the server selected in the onopen method:
connection.onopen = function () {
if (ws.protocol == 'json') {
console.log('Json was selected');
As soon as the connection is declared you can also add the usual callbacks to listen for
messages or errors:
connection.onerror = function (error) {
console.log('Error ' + error);
connection.onmessage = function (event) {
Search WWH ::

Custom Search