WebSockets are a rising technology that solves one of the great needs of web development - full duplex communication between a browser (or a different client) and a server.

Let's imagine a simple scenario - live web chat. In the past, you'd probably use AJAX and polling to make new posts appear in realtime. The downside is that implementing all that is not entirely easy and it tends to put a lot of strain on the server.

This article will show you how to implement a simple web chat using WebSockets, thus eliminating the above problems. We will be using the Tornado web server with the Flask framework, producing a pure Python solution. To get the maximum out of Python 2.x, we will utilize the python27 Software Collection (SCL). We will also need a newer version of Firefox that supports WebSocket technology, so that we can test from the RHEL 6 machine that we're developing on.

Installation

First, let's get Firefox. Firefox fully supports WebSocket from version 11, but we want to be fresh, so let's grab version 19 (64 bit / 32 bit). Just download the archive, unpack it, go to the firefox dir and run ./firefox. If you're already running an instance of a different version of Firefox, you will need to run ./firefox -no-remote -P and create a new profile for the downloaded Firefox - you can't run two different versions with the same profile.

Second, we need to install the python27 SCL. Download the repofile and add it to your /etc/yum.repos.d. Then just use yum install python27 and that's it.

The last step is installing Flask and Tornado. First, let's switch to the SCL:

scl enable python27 bash

Then create a virtualenv for the new project, enable it and install dependencies:

virtualenv --system-site-packages flask-websocket-test/venv
source flask-websocket-test/venv/bin/activate
pip install flask tornado

That's it, the environment is ready.

Implementing the Server Logic

Let's start by creating the server part. First create the directory structure:

mkdir -p ~/flask-websocket-test/templates

Then create ~/flask-websocket-test/__init__.py file:

import flask

import tornado
import tornado.websocket
import tornado.wsgi

app = flask.Flask(__name__)

@app.route('/')
def index():
    return flask.render_template('index.html')

class ChatWebSocket(tornado.websocket.WebSocketHandler):
    clients = []

    def open(self):
        ChatWebSocket.clients.append(self)

    def on_message(self, message):
        for client in ChatWebSocket.clients:
            client.write_message(message)

    def on_close(self):
        ChatWebSocket.clients.remove(self)

tornado_app = tornado.web.Application([
    (r'/websocket', ChatWebSocket),
    (r'.*', tornado.web.FallbackHandler, {'fallback': tornado.wsgi.WSGIContainer(app)})
])

tornado_app.listen(5000)
tornado.ioloop.IOLoop.instance().start()

Some comments:

  • Lines 1-5 are the necessary imports.
  • Lines 7-11 construct a simple Flask app that renders the templates/index.html template (we will get to that later).
  • Lines 13-24 are the important ones. Class ChatWebSocket has three methods, that every tornado.websocket.WebSocketHandler needs to override. It operates with class variable clients, that holds all active instances of this class.
    • open method on line 16 is called when a new client is connected and it adds the client to the clients list.
    • on_message method on line 19 writes a message that one client sends to all clients.
    • on_close removes the closing client from the clients list
  • Lines 26-29 just tell Tornado to route /websocket to ChatWebsocketHandler and the rest to the Flask WSGI application.
  • Finally, on lines 31-32 we instantiate and start the IOLoop (so we can run the server by running __init__.py file).

Implementing the index.html Template

The last step of the implementation is the creation of the ~/flask-websocket-test/templates/index.html template:

<html>
  <head>
    <title>WebSocketTest</title>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
    <script type="text/javascript">
      ws = new WebSocket("ws://127.0.0.1:5000/websocket");
      ws.onmessage = function(msg) {
        $("#discussion").prepend("<p>" + msg.data + "<p>");
      };
      ws.onerror = function(evt) {
        alert("ERROR: "+evt.data);
      };
      function send_message() {
        msg = "<b>" + $("#nick").val() + ": </b>" + $("#message").val();
        ws.send(msg);
      }
    </script>
  </head>
  <body>
    <form>
      <dl>
        <dt>Your nick:</dt><dd><input type="text" id="nick" value="nick"></dd>
        <dt>Message:</dt><dd><textarea id="message"></textarea>
      </dl>
      <button onclick="send_message(); return false;">foo</button>
    </form>
    <div id="discussion">
    </div>
  </body>
</html>

What's going on in there?

  • We're using jQuery to get things done quickly and nicely with JavaScript.
  • Method ws.onmessage (lines 7-9) is called whenever the server sends some info through the WebSocket.
  • Function send_message (lines 13-16) is used to send a message to the server through the WebSocket.
  • Remember to replace 127.0.0.1 for the actual IP address/domain name of your server if you want to connect from other machines.

Testing

Run the application with python ~/flask-websocket-test/__init__.py (don't forget to be in a SCL-enabled shell). Now open two tabs (or windows) of the downloaded Firefox and enjoy the chat.
And that's it. You just created your first WebSocket server with 32 lines of Python code and 30 lines of html and JavaScript.

Last updated: November 2, 2023