barbarian meets coding

WebDev, UX & a Pinch of Fantasy

HTML5 Web Sockets

This article is part of my personal wiki where I write personal notes while I am learning new technologies. You are welcome to use it for your own learning!

The web sockets API allows to establish socket connections between a browser and a server. As opposed of the stateless, disconnected, common HTTP request/response cycle in which a client communicates with the server, web sockets allows for a persistent connection in which any of the parties, client or server, can send data to the other at any time. (Really useful for real time web applications where the server sends data as it appears to the client).

The core of the API is the WebSocket object. You can create a new web socket as illustrated below:

1
2
3
4
5
6
7
8
9
10
// web socket echo server
// useful for testing web sockets
// note the ws:// that represents the URL schema
var connection = new WebSocket('ws://echo.websocket.org');

// you can also use a secure connection using wss://
var connection = new WebSocket('wss://echo.websocket.org');

// and you can also specify subprotocols
var connection = new WebSocket('wss://echo.websocket.org', ['soap', 'xmpp']);

In order to be able to be able to handle messages over web sockets you need to handle some events:

1
2
3
4
5
6
7
8
9
connection.onopen = function() {
    connection.send('hello! The connection is open');
}
connection.onerror = function(error){
    console.error('Houston we\'ve got a problem');
}
connection.onmessage = function(e){
    console.log('Message received from server: ', e.data);
};

You can find an example of web sockets in JsFiddle.

References

Comments