tornado.websocket — Bidirectional communication to the browser

Implementation of the WebSocket protocol.

WebSockets allow for bidirectional communication between the browser and server.


The WebSocket protocol was recently finalized as RFC 6455 and is not yet supported in all browsers. Refer to for details on compatibility. In addition, during development the protocol went through several incompatible versions, and some browsers only support older versions. By default this module only supports the latest version of the protocol, but optional support for an older version (known as “draft 76” or “hixie-76”) can be enabled by overriding WebSocketHandler.allow_draft76 (see that method’s documentation for caveats).

class tornado.websocket.WebSocketHandler(application, request, **kwargs)[source]

Subclass this class to create a basic WebSocket handler.

Override on_message to handle incoming messages, and use write_message to send messages to the client. You can also override open and on_close to handle opened and closed connections.

See for details on the JavaScript interface. The protocol is specified at

Here is an example WebSocket handler that echos back all received messages back to the client:

class EchoWebSocket(websocket.WebSocketHandler):
    def open(self):
        print "WebSocket opened"

    def on_message(self, message):
        self.write_message(u"You said: " + message)

    def on_close(self):
        print "WebSocket closed"

WebSockets are not standard HTTP connections. The “handshake” is HTTP, but after the handshake, the protocol is message-based. Consequently, most of the Tornado HTTP facilities are not available in handlers of this type. The only communication methods available to you are write_message(), ping(), and close(). Likewise, your request handler class should implement open() method rather than get() or post().

If you map the handler above to /websocket in your application, you can invoke it in JavaScript with:

var ws = new WebSocket("ws://localhost:8888/websocket");
ws.onopen = function() {
   ws.send("Hello, world");
ws.onmessage = function (evt) {

This script pops up an alert box that says “You said: Hello, world”.

Event handlers[source]

Invoked when a new WebSocket is opened.

The arguments to open are extracted from the tornado.web.URLSpec regular expression, just like the arguments to tornado.web.RequestHandler.get.


Handle incoming messages on the WebSocket

This method must be overridden.


Invoked when the WebSocket is closed.

If the connection was closed cleanly and a status code or reason phrase was supplied, these values will be available as the attributes self.close_code and self.close_reason.

Changed in version 3.3: Added close_code and close_reason attributes.


Invoked when a new WebSocket requests specific subprotocols.

subprotocols is a list of strings identifying the subprotocols proposed by the client. This method may be overridden to return one of those strings to select it, or None to not select a subprotocol. Failure to select a subprotocol does not automatically abort the connection, although clients may close the connection if none of their proposed subprotocols was selected.


WebSocketHandler.write_message(message, binary=False)[source]

Sends the given message to the client of this Web Socket.

The message may be either a string or a dict (which will be encoded as json). If the binary argument is false, the message will be sent as utf8; in binary mode any byte string is allowed.

If the connection is already closed, raises WebSocketClosedError.

Changed in version 3.2: WebSocketClosedError was added (previously a closed connection would raise an AttributeError)

WebSocketHandler.close(code=None, reason=None)[source]

Closes this Web Socket.

Once the close handshake is successful the socket will be closed.

code may be a numeric status code, taken from the values defined in RFC 6455 section 7.4.1. reason may be a textual message about why the connection is closing. These values are made available to the client, but are not otherwise interpreted by the websocket protocol.

The code and reason arguments are ignored in the “draft76” protocol version.

Changed in version 3.3: Added the code and reason arguments.



Override to enable support for the older “draft76” protocol.

The draft76 version of the websocket protocol is disabled by default due to security concerns, but it can be enabled by overriding this method to return True.

Connections using the draft76 protocol do not support the binary=True flag to write_message.

Support for the draft76 protocol is deprecated and will be removed in a future version of Tornado.


Return the url scheme used for this request, either “ws” or “wss”.

This is normally decided by HTTPServer, but applications may wish to override this if they are using an SSL proxy that does not provide the X-Scheme header as understood by HTTPServer.

Note that this is only used by the draft76 protocol.


Set the no-delay flag for this stream.

By default, small messages may be delayed and/or combined to minimize the number of packets sent. This can sometimes cause 200-500ms delays due to the interaction between Nagle’s algorithm and TCP delayed ACKs. To reduce this delay (at the expense of possibly increasing bandwidth usage), call self.set_nodelay(True) once the websocket connection is established.

See BaseIOStream.set_nodelay for additional details.

New in version 3.1.


WebSocketHandler.async_callback(callback, *args, **kwargs)[source]

Obsolete - catches exceptions from the wrapped function.

This function is normally unncecessary thanks to tornado.stack_context.[source]

Send ping frame to the remote end.


Invoked when the response to a ping frame is received.

exception tornado.websocket.WebSocketClosedError[source]

Raised by operations on a closed connection.

New in version 3.2.

Client-side support

tornado.websocket.websocket_connect(url, io_loop=None, callback=None, connect_timeout=None)[source]

Client-side websocket support.

Takes a url and returns a Future whose result is a WebSocketClientConnection.

Changed in version 3.2: Also accepts HTTPRequest objects in place of urls.

class tornado.websocket.WebSocketClientConnection(io_loop, request)[source]

WebSocket client connection.

This class should not be instantiated directly; use the websocket_connect function instead.

close(code=None, reason=None)[source]

Closes the websocket connection.

code and reason are documented under WebSocketHandler.close.

New in version 3.2.

Changed in version 3.3: Added the code and reason arguments.

write_message(message, binary=False)[source]

Sends a message to the WebSocket server.


Reads a message from the WebSocket server.

Returns a future whose result is the message, or None if the connection is closed. If a callback argument is given it will be called with the future when it is ready.