Server-side implementation of the WebSocket protocol.
WebSockets allow for bidirectional communication between the browser and server.
Warning
The WebSocket protocol is still in development. This module currently implements the “hixie-76” and “hybi-10” versions of the protocol. See this browser compatibility table on Wikipedia.
Subclass this class to create a basic WebSocket handler.
Override on_message to handle incoming messages. You can also override open and on_close to handle opened and closed connections.
See http://dev.w3.org/html5/websockets/ for details on the JavaScript interface. This implement the protocol as specified at http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-10 The older protocol version specified at http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76. is also supported.
Here is an example Web Socket 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"
Web Sockets 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() 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) {
alert(evt.data);
};
This script pops up an alert box that says “You said: Hello, world”.
Handle incoming messages on the WebSocket
This method must be overloaded
Base class for WebSocket protocol versions.
Implementation of the WebSockets protocol, version hixie-76.
This class provides basic functionality to process WebSockets requests as specified in http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76
Implementation of the WebSocket protocol, version 8 (draft version 10).
Compare http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-10