Getting started with WebSockets using Python and Tornado

Using WebSockets in Python with Tornado is very easy. Today I’ll show you how to build a very simple application that will demonstrate the basics of getting everything working.

Note: Make sure you are using a fairly new web browser, I tested this on the latest version of Firefox but Chrome and Safari should work as well. I’m using Python 2.7.4 but this should work on Python 3.x with little or no modifications. Finally, I’m doing this on Ubuntu 13 but this will work on OS X as well as other Linux distros. Modify as required.

Project Setup: I like to use Virtualenv to keep my global site-packages clean, this is typically how I work with any Python project. Feel free to set your project up as you see fit.

To get started create a new folder calling it whatever you wish. Inside of that folder add another folder called templates. In the root project folder create a file called ws_app.py and in the templates folder add a file called index.html.

Make sure you have Tornado installed, you can do this easily with the following command:

$ pip install tornado

The contents of index.html will look like the following:

Tornado WebSocketsMessage to Send:

As you can see this is nothing fancy and very minimal JavaScript – just enough to make this work. Essentially you can enter text and send it to the Tornado server and have that message sent back to you.

6 Responses to Getting started with WebSockets using Python and Tornado

Great tutorial! This was my first foray into websockets and I liked how you stripped it down to the bare minimum.

I can’t help thinking, though, for this particular use, why not just use XHR? I thought the only advantage of using a websocket is that it requires no request to be sent. If you’re sending a request to get a response, we already have things that can do that!

This article was only to show in simplest form how to get WebSockets and Tornado working together. I didn’t even use jQuery just to keep it as simple as possible.

With AJAX, you have to poll for updates. With WebSockets the message can be sent immediately to the connected client(s). You can obviously run into latency and scaling issues with each so its going to depend on what your trying to accomplish and which is the best solution to pursue. This is where things like caching and load balancing start to become important as an application needs to scale.

Thank you for tutorial,it’s very useful for me . But I get some problem when I run python ws_app.py,nothing happend but start a new line .when I type http://localhost:8080 in the browser,it shows “Firefox can’t establish a connection to the server at localhost:8080.”,I guess the server isn’t started,but I don’t know how to figure it out.Could you give me some advices?