Fork me on GitHub

WebSocket

Realtime communication for the web

Esta página estaba disponible en español también (traducido por Maria Ramos de Webhostinghub.com/support/edu). Sin embargo aparentemente no está disponible más.

This is an HTML5 WebSocket community resource which you can edit, with information about the WebSocket protocol and API, tutorials on how to write WebSocket clients and servers, and a list of available WebSocket frameworks and libraries.

What is WebSocket?

WebSocket is a new standard for realtime communication on the web, which is part of the HTML5 umbrella. WebSocket is a simple JavaScript API and accompanying protocol that allows you to create "web sockets", capable of bi-directional full-duplex communication over a persistent TCP connection (socket). These "web sockets", unlike traditional TCP sockets, are very easy to use.

The most recent (IETF standard) version of the WebSocket TCP protocol is supported in modern browsers such as Internet Explorer 10, Firefox 11, and Chrome 16.

Live Demo

Here's a demo rigged up to the echo server example from the next section, so you can test if your browser supports WebSocket. (Note: I'm having trouble with the server at the moment, so if it doesn't work, it's probably my fault)

State: Not yet loaded

Writing a client and server

Writing a WebSocket application in JavaScript couldn't be easier. Simply establish a connection, and hook into the open, error, message and close events as necessary. Remember, WebSocket is subject to the same-origin policy, like AJAX. This means if you want to test your client locally, you'll need to run a web server (e.g. python -m SimpleHTTPServer). Here's a simple client, which should work in newer browsers:

var socket = new WebSocket('ws://localhost:8080/');
socket.onopen = function () {
    alert('Connected!');
};
socket.onmessage = function (event) {
    alert('Received data: ' + event.data);
    socket.close();
};
socket.onclose = function () {
    alert('Lost connection!');
};
socket.send('hello, world!');

Aside from handling the error event (with onerror), that's all you need for a functional WebSocket client.

There are libraries for helping to write WebSocket server applications, compatible with various languages and frameworks. Here's a simple echo server written in Python using Twisted and txWS:

from twisted.internet import protocol, reactor
from txws import WebSocketFactory

class Echo(protocol.Protocol):
    def dataReceived(self, data):
        self.transport.write(data)

class EchoFactory(protocol.Factory):
    def buildProtocol(self, addr):
        return Echo()

reactor.listenTCP(8080, WebSocketFactory(EchoFactory()))
reactor.run()

How WebSocket works

Like standard HTTP, WebSocket by default uses port 80 in the clear and 443 over SSL. The WebSocket client establishes an HTTP connection and requests to switch the protocol using the HTTP Upgrade mechanism, and then follows a handshake protocol to ensure both client and server support WebSocket. Since WebSocket connections start off as HTTP, WebSocket can work through many existing proxies and firewalls, unlike some other protocols.

Once the connection is established, messages are sent as "frames", either text or binary format, in both directions. These are the data strings you send and receive in JavaScript.

WebSocket URIs have the same basic format as HTTP URIs, but with a different URI scheme: ws://hostname:port/path, e.g. ws://example.com/echo or ws://example.net:8080. The path can be used to distinguish the purpose of the connection, however some servers ignore it. Secure WebSocket (WebSocket over SSL/TLS) URIs begin with wss:// instead of ws://.

Should you use WebSocket?

WebSocket provides many benefits compared to alternatives (e.g. long-polling or Comet), such as much lower overhead, persistent connections, and low latency. That said, WebSocket is not a mature technology, and older browsers do not support it. If you are targeting only modern, HTML5-compatible browsers, there is no reason to avoid it. However, should you need to support older browsers, there are various solutions to help you, which use Flash or long-polling, e.g. SockJS, web-socket-js or Socket.IO.

Server libraries and frameworks

This list is far from comprehensive. There are many WebSocket libraries out there. If you'd like to extend it, send a pull request or contact me.

C++

C++/Qt

C#/.NET

Go

Haskell

Java

Node.js

Objective-C/iOS

Perl

PHP

Python

Ruby

Other

More information

More information on WebSocket can be found at these places:

About me

This is part of my website. You can email me at ajf@ajf.me, and I'm also on Twitter. The source code of this website is available on GitHub, if you want to contribute.