Tornado – Web Sockets

 

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


import tornado.ioloop
import tornado.web
import tornado.websocket
class Socket(tornado.websocket.WebSocketHandler):
def open(self):
print "Socket opened"
def on_message(self, message):
self.write_message("Msg is " + message)
def on_close(self):
print "Socket closed"
class Main(tornado.web.RequestHandler):
def get(self):
print "It Works!"
application = tornado.web.Application([
(r"/", Main),
(r"/socket", Socket),
],debug=True)


from ws4py.client.threadedclient import WebSocketClient
class EchoClient(WebSocketClient):
def opened(self):
self.send("Hello Chetan")
def closed(self, code, reason):
print "Closed down", code, reason
def received_message(self, m):
print "Received from server: %s" % (str(m))
if __name__ == '__main__':
try:
ws = EchoClient('http://localhost:8888/socket', protocols=['http-only', 'chat'])
ws.daemon = False
ws.connect()
except KeyboardInterrupt:
ws.close()
finally:
ws.close()

view raw

ws4pyclient.py

hosted with ❤ by GitHub

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’

 

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.