WebSocket (RFC 6455) protocol provides bi-directional (or duplex) communication between web server and browser. Communication typically happens over a single TCP connection and is used to facilitate interaction between web server and browser like live streaming and real time content delivery. It is crucial to note that WebSocket is non standard HTTP connection where although the handshake happens through Http, but the communication i message based.

Please note: WebSocket protocol is different from socket programming. Different libraries (like ws4py) are available in Python that can act as client for websocket communication.

Tornado provides a tornado.websocket.WebSocketHandler class to create WebSocket Handler. Methods like get() or post() won’t work here; instead following methods need to be overridden by the server developer

open() / close() – handle open or closed sockets

on_message() / write_message() – handles messages

Here’s an example implementation along with ws4py client

In this example,

  • You start a WebSocket Handler by running tornadowebsocket.py. This handler implements open(), on_message and close() methods
  • When ws4pyclient.py is run in another terminal, message ‘Hello Chetan’ is sent from opened() method to web server
  • This opens up the server side websocket and message ‘Socket opened’ is printed from open() method
  • on_message() of server sends a message to the client with self.write_message() and closes the socket with on_close() method and print ‘Socket closed’
  • The message sent by the server is then received by the client in received_message() method where the client prints ‘Received from server: Hello Chetan’
  • Client then is closed with closed() method by printing ‘Closed down’