Over a million developers have joined DZone.

WebSockets in 5 minutes

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

 HTTP is by design an asymmetric protocol: clients can contact the server whenever they want (without the user having to issue a command, thanks to Ajax requests). The server instead cannot normally send updates at the client at the time of its choosing.

Connections are made as HTTP requests, GET or POST in nearly all web browsers, from the client to the server, and never the opposite. This mechanism simplifies the protocol in many ways, but raises issues whenever a real-time interaction is desiderable. How to implement a chat in a browser?

There are some work arounds but...

The simplest solution is polling the server continuously: every 5 seconds we send a request, and the server tells us which messages are arrived in the chat room. However this raises the load on the server, which must manage a huge number of new connections at the same time.

A slightly better model is long polling (and other similar techniques which collectively go under the name of Comet), where each connection made by the client is kept open until there are some data to return to the client. The connection may also have a timeout, but it's very simple to just restart one after a 60-second timeout has expired.

The problem with both styles is that they are not really scalable with the current HTTP servers. Apache dedicates one process to each connection - if you have to keep open a process for every user in a chat, the server will quickly halt. There are however different HTTP servers, like CouchDB and Node.js, which do not allocate multiple processes and are capable of handling this large number of simultaneous open connections.


Since we already have to change some server-side infrastructure to support the server pushing to the client on certain events, let's do it with a standard protocol. HTML 5 WebSockets promise a bidirectional full-duplex connection, which is not closed after the first data returned by the server along with headers, but remains open like any TCP connection.

Technically speaking in fact, WebSockets are a mechanism for tunneling a TCP connection over HTTP: you can send whatever you want in the communication channel, but the communication is wrapped into a text stream with HTTP headers such as Host and Origin.

A cool thing about using HTTP nowadays, apart from the universal client (the browser), is its friendship with proxies; in fact, proxies are often the target of browsers connections, which with an HTTP CONNECT command instruct it to open a TCP connection towards some other server, passing through NAT.

WebSockets use ws:// and wss:// Urls as identifiers. There is a lot less overhead in the communication, as at each interaction you can avoid sending HTTP headers in both request and response. The interaction with the DOM and other browser components is still asynchronous (defined via events and callbacks), so it's just a nice upgrade over Ajax requests.

You can communicate via a WebSocket via events such as onopen, onmessage, onclose, and methods like send() and close(). This Api is consistent with that of WebWorkers. This is an example of the Api taken from WebSocket.org:

var myWebSocket = new WebSocket("ws://www.websockets.org");
myWebSocket.onmessage = function(evt) { alert( "Received Message: "  +  evt.data); };
myWebSocket.send("Hello Web Sockets!");


Ora incomincian le dolenti note - now begin the notes of woe.

Chrome is one of the few browsers supporting WebSockets in a stable release, along with Safari 5. Firefox 4 and Opera has the protocol disabled by default due to secutiry issues, and let's not talk about Internet Explorer.

Fortunately, there is the possibility of emulating via client-side libraries, by falling back on Ajax or invisible iframes where WebSockets are not available. There are two libraries to include here:

They will probably require also a different server setup, but I think the great issue is getting the client to work, while upgrading a server is always feasible.


WebSockets are not really a production-ready technology, but are on the verge of innovation (and you can always fallback until browsers catch up). We'll see if the innovation works well or it is a straining on the resource-oriented model of HTTP.

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.


Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}