WebSockets with Tornado

WebSockets are a new protocol for client-server communication proposed in the HTML 5 spec. The protocol is still a draft, and only the most recent web browsers support it. However, its benefits are significant enough that we will see the protocol become more popular as more browsers begin to support it. (As always with web development, it’s prudent to adhere to the pragmatic strategy of relying on new features when available and falling back on older technology when necessary.)

The WebSocket protocol provides bidirectional communication over a persistent connection between a client and server. The protocol itself uses a new ws:// URL scheme, but is implemented on top of standard HTTP. By using the standard HTTP and HTTPS ports, it avoids all kinds of problems introduced when connecting to sites from networks that sit behind web proxies. The HTML 5 spec not only describes the communication protocol itself, but also the browser APIs that are required to write client-side code that use WebSockets.

Since WebSocket support is already supported in some of the latest browsers and since Tornado helpfully provides a module for it, it’s worth seeing how to implement applications that use WebSockets.

Tornado’s WebSocket Module

Tornado provides a WebSocketHandler class as part of the websocket module. The class provides hooks for WebSocket events and methods to communicate with the connected client. The open method is called when a new WebSocket connection is opened, and ...

Get Introduction to Tornado now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.