Home »
Python
How to implement a WebSocket server using Tornado?
WebSocket in Python: Here, we are going to learn how to implement a WebSocket server using Tornado?
Submitted by Sapna Deraje Radhakrishna, on September 17, 2019
What is Tornado?
Tornado is a python web framework and asynchronous networking library. It is scalable and non-blocking. It specializes in dealing with event-driven networking. As tornado supports concurrent connections, naturally, a server can take advantage of this behavior and handle a lot of web socket connections within a single node.
What is Websocket?
WebSocket is a protocol that provides full-duplex communication channels over a single TCP connection. The behavior of the open socket makes a web connection stateless and facilitates the real-time data transfer to and from the server.
WebSockets are designed to be used in web-browsers and servers. A connection is opened once and messages can travel to-fro multiple times before the connection is closed.
Install Tornado
Installing the tornado is rather simple in a virtual environment using pip.
- Create a virtual environment
python3 -m venv /path/to/virtual/environment
>> python3 -m venv venv
- Source the virtual environment
>> source venv/bin/activate
- Install the websocket-client using pip
>> (venv) pip3 install tornado
Using cached https://files.pythonhosted.org/packages/30/78/2d2823598496127b21423baffaa186b668f73cd91887fcef78b6eade136b/tornado-6.0.3.tar.gz
Requirement already satisfied: six in ./venv/lib/python3.7/site-packages (from websocket_client==0.56.0->-r requirements.txt (line 1)) (1.12.0)
Installing collected packages: tornado
Running setup.py install for tornado ... done
Successfully installed tornado-6.0.3
Python example to start a web socket server using Tornado library
'''
This module hosts a websocket server using tornado
libraries
'''
import tornado.web
import tornado.httpserver
import tornado.ioloop
import tornado.websocket as ws
from tornado.options import define, options
import time
define('port', default=4041, help='port to listen on')
class web_socket_handler(ws.WebSocketHandler):
'''
This class handles the websocket channel
'''
@classmethod
def route_urls(cls):
return [(r'/',cls, {}),]
def simple_init(self):
self.last = time.time()
self.stop = False
def open(self):
'''
client opens a connection
'''
self.simple_init()
print("New client connected")
self.write_message("You are connected")
def on_message(self, message):
'''
Message received on the handler
'''
print("received message {}".format(message))
self.write_message("You said {}".format(message))
self.last = time.time()
def on_close(self):
'''
Channel is closed
'''
print("connection is closed")
self.loop.stop()
def check_origin(self, origin):
return True
def initiate_server():
#create a tornado application and provide the urls
app = tornado.web.Application(web_socket_handler.route_urls())
#setup the server
server = tornado.httpserver.HTTPServer(app)
server.listen(options.port)
#start io/event loop
tornado.ioloop.IOLoop.instance().start()
if __name__ == '__main__':
initiate_server()
The above code will start the server on localhost and port as 4041.
Connect to the server using a websocket client code (example below),
from websocket import create_connection
def short_lived_connection():
ws = create_connection("ws://localhost:4040/")
print("Sending 'Hello Server'...")
ws.send("Hello, Server")
print("Sent")
print("Receiving...")
result = ws.recv()
print("Received '%s'" % result)
ws.close()
if __name__ == '__main__':
short_lived_connection()
Output (Client side):
>>Sending 'Hello, Server'...
>>Sent
>>Receiving...
>>Received 'You are connected'
Output (Server side):
>>New client connected
>>received message Hello, Server
>>connection is closed
References: