2014-02-10T03:46:26Z

Easy WebSockets with Flask and Gevent

This weekend I decided to take a short vacation from my book writing effort and spend time on a project I wanted to work on for a long time. The result of this effort is a brand new Flask extension that I think is pretty cool.

I'm happy to introduce Flask-SocketIO, a very easy to use extension that enables WebSocket communications in Flask applications.

What is WebSocket?

WebSocket is a new communication protocol introduced with HTML5, mainly to be implemented by web clients and servers, though it can also be implemented outside of the web.

Unlike HTTP connections, a WebSocket connection is a permanent, bi-directional communication channel between a client and the server, where either one can initiate an exchange. Once established, the connection remains available until one of the parties disconnects from it.

WebSocket connections are useful for games or web sites that need to display live information with very low latency. Before this protocol existed there were other much less efficient approaches to achieve the same result such as Comet.

The following web browsers support the WebSocket protocol:

  • Chrome 14
  • Safari 6
  • Firefox 6
  • Internet Explorer 10

What is SocketIO?

SocketIO is a cross-browser Javascript library that abstracts the client application from the actual transport protocol. For modern browsers the WebSocket protocol is used, but for older browsers that don't have WebSocket SocketIO emulates the connection using one of the older solutions, the best one available for each given client.

The important fact is that in all cases the application uses the same interface, the different transport mechanisms are abstracted behind a common API, so using SocketIO you can be pretty much sure that any browser out there will be able to connect to your application, and that for every browser the most efficient method available will be used.

What about Flask-Sockets?

A while ago Kenneth Reitz published Flask-Sockets, another extension for Flask that makes the use of WebSocket accessible to Flask applications.

The main difference between Flask-Sockets and Flask-SocketIO is that the former wraps the native WebSocket protocol (through the use of the gevent-websocket project), so it can only be used by the most modern browsers that have native support. Flask-SocketIO transparently downgrades itself for older browsers.

Another difference is that Flask-SocketIO implements the message passing protocol exposed by the SocketIO Javascript library. Flask-Sockets just implements the communication channel, what is sent on it is entirely up to the application.

Flask-SocketIO also creates an environment for event handlers that is close to that of regular view functions, including the creation of application and request contexts. There are some important exceptions to this explained in the documentation, however.

A Flask-SocketIO Server

Installation of Flask-SocketIO is very simple:

$ pip install flask-socketio

Below is an example Flask application that implements Flask-SocketIO:

from flask import Flask, render_template
from flask_socketio import SocketIO, emit

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)

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

@socketio.on('my event')
def test_message(message):
    emit('my response', {'data': message['data']})

@socketio.on('my broadcast event')
def test_message(message):
    emit('my response', {'data': message['data']}, broadcast=True)

@socketio.on('connect')
def test_connect():
    emit('my response', {'data': 'Connected'})

@socketio.on('disconnect')
def test_disconnect():
    print('Client disconnected')

if __name__ == '__main__':
    socketio.run(app)

The extension is initialized in the usual way, but to simplify the start up of the server a custom run() method is used instead of flask run or app.run(). This method starts the eventlet or gevent servers if they are installed. Using gunicorn with the eventlet or gevent workers should also work. The run() method takes optional host and port arguments, but by default it will listen on localhost:5000 like Flask's development web server.

The only traditional route in this application is /, which serves index.html, a web document that contains the client implementation of this example.

To receive WebSocket messages from the client the application defines event handlers using the socketio.on decorator.

The first argument to the decorator is the event name. Event names 'connect', 'disconnect', 'message' and 'json' are special events generated by SocketIO. Any other event names are considered custom events.

The 'connect' and 'disconnect' events are self-explanatory. The 'message' event delivers a payload of type string, and the 'json' and custom events deliver a JSON payload, in the form of a Python dictionary.

To send events a Flask server can use the send() and emit() functions provided by Flask-SocketIO. The send() function sends a standard message of string or JSON type to the client. The emit() function sends a message under a custom application-defined event name.

Messages are sent to the connected client by default, but when including the broadcast=True optional argument all clients connected to the namespace receive the message.

A SocketIO Client

Ready to try your hand at some Javascript? The index.html page used by the example server contains a little client application that uses jQuery and SocketIO. The relevant code is shown below:

$(document).ready(function(){
    var socket = io();
    socket.on('my response', function(msg) {
        $('#log').append('<p>Received: ' + msg.data + '</p>');
    });
    $('form#emit').submit(function(event) {
        socket.emit('my event', {data: $('#emit_data').val()});
        return false;
    });
    $('form#broadcast').submit(function(event) {
        socket.emit('my broadcast event', {data: $('#broadcast_data').val()});
        return false;
    });
});

The socket variable is initialized with a SocketIO connection to the server. If the Socket.IO server is hosted at a different URL than the HTTP server, then you can pass a connection URL as an argument to io().

The socket.on() syntax is used in the client side to define an event handler. In this example a custom event with name 'my response' is handled by adding the data attribute of the message payload to the contents of a page element with id log. This element is defined in the HTML portion of the page.

The next two blocks override the behavior of two form submit buttons so that instead of submitting a form over HTTP they trigger the execution of a callback function.

For the form with id emit the submit handler emits a message to the server with name 'my event' that includes a JSON payload with a data attribute set to the value of the text field in that form.

The second form, with id broadcast does the same thing, but sends the data under a different event name called 'my broadcast event'.

If you now go back to the server code you can review the handlers for these two custom events. For 'my event' the server just echoes the payload back to the client in a message sent under event name 'my response', which is handled by showing the payload in the page. The event named 'my broadcast event' does something similar, but instead of echoing back to the client alone it broadcasts the message to all connected clients, also under the 'my response' event.

You can view the complete HTML document in the GitHub repository.

Running the Example

To run this example you first need to download the code from GitHub. For this you have two options:

The example application is in the example directory, so cd to it to begin.

To keep your global Python interpreter clean it is a good idea to make a virtual environment:

$ virtualenv venv
$ . venv/bin/activate

Then you need to install the dependencies:

(venv) $ pip install -r requirements.txt

Finally you can run the application:

(venv) $ python app.py

Now open your web browser and navigate to http://localhost:5000 and you will get a page with two forms as shown in the following screenshot:

Any text you submit from any of the two text fields will be sent to the server over the SocketIO connection, and the server will echo it back to the client, which will append the message to the "Receive" part of the page, where you can already see the message sent by the 'connect' event handler from the server.

Things get much more interesting if you connect a second browser to the application. In my case I'm testing this with Firefox and Chrome, but any two browsers that you run on your machine will do. If you prefer to access the server from multiple machines you can do that too, but you first need to change the start up command to socketio.run(app, host='0.0.0.0') so that the server listens on the public network interface.

With two or more clients when you submit a text from the form on the left only the client that submitted the message gets the echoed response. If you submit from the form on the right the server broadcasts the message to all connected clients, so all get the reply.

If a client disconnects (for example if you close the browser window) the server will detect it a few seconds later and send a disconnect event to the application. The console will print a message to that effect.

Final Words

For a more complete description of this extension please read the documentation. If you want to make improvements to it feel free to fork it and then submit a pull request.

I hope you make cool applications with this extension. I can tell you that I had a lot of fun implementing this extension.

If you make something with it feel free to post links in the comments below.

Miguel

495 comments

  • #101 Kevin said 2014-05-14T23:59:06Z

    I was looking for a way to broadcast a messsage to all clients except the sender, and it seems like socketio.emit('message', data, broadcast=True) does the trick. Is this documented anywhere? Also, I feel that the syntax is inconsistent with the original: https://github.com/LearnBoost/socket.io/wiki/How-do-I-send-a-response-to-all-clients-except-sender%3F

  • #102 Kevin said 2014-05-15T00:13:32Z

    scratch that, it is documented and it doesn't do what I think it does. Is there a way to get that behavior?

  • #103 Miguel Grinberg said 2014-05-15T04:32:24Z

    @ben: when you use gevent you use a single process. A single gevent process can handle lots of clients using greenlets.

  • #104 Miguel Grinberg said 2014-05-15T04:34:00Z

    @Kevin: the broadcast message sends to all, including the sender. The easy way to do this is to add a signature of the sender to the message, so that on the receiving side the sender can filter the message out. A more efficient way would be to iterate over all the clients and send to everyone except the sender. Look at the implementation of the broadcast method to see how this can be done.

  • #105 Lee said 2014-05-15T15:41:53Z

    Have you seen: http://django-websocket-redis.readthedocs.org/en/latest/ on ways to get flask-websockets to work with uWSGI?

  • #106 Miguel Grinberg said 2014-05-15T21:31:58Z

    @Lee: the problem is not in the web socket layer, which is supported by uWSGI. The Socket.IO protocol requires server side support on top of web sockets, and this is implemented in a subclassed gevent server. As far as I can see there is no way to point uWSGI at a custom gevent server class, since it runs its own event loop.

  • #107 Anubhav said 2014-05-22T15:08:13Z

    Hi, Thanks for the tutorial. I am having the error 'No handlers could be found for logger "socketio.virtsocket' when I am keeping the javascript code into a seperate js file. I don't want to keep the js code inside html. Is there any solution for it? Thanks

  • #108 Miguel Grinberg said 2014-05-23T05:55:13Z

    @Anubhav: what's the stack trace of the error?

  • #109 beatle said 2014-05-25T18:47:15Z

    Hey, how would i go about sending a message to all clients except the initiator of the event

  • #110 Miguel Grinberg said 2014-05-25T18:51:41Z

    @beatle: that is currently not an available option. What I do in such a case is add the id of the sender to the message, so that when the sender gets the message it can filter it.

  • #111 Weihong Guan said 2014-05-27T10:13:51Z

    if using flask-socketio, how to run with gunicorn with multi workers? Traceback (most recent call last): File "/home/agu/workspace/busykoala-mongo/venv/local/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 131, in handle_request respiter = self.wsgi(environ, resp.start_response) File "/home/agu/workspace/busykoala-mongo/venv/local/lib/python2.7/site-packages/flask/app.py", line 1836, in call return self.wsgi_app(environ, start_response) File "/home/agu/workspace/busykoala-mongo/venv/local/lib/python2.7/site-packages/werkzeug/contrib/fixers.py", line 144, in call return self.app(environ, start_response) File "/home/agu/workspace/busykoala-mongo/venv/local/lib/python2.7/site-packages/flask_socketio/init.py", line 25, in call raise RuntimeError('You need to use a gevent-socketio server.') RuntimeError: You need to use a gevent-socketio server.

  • #112 Miguel Grinberg said 2014-05-27T14:15:38Z

    @Weihong: The gevent based servers handle multiple users with greenlets, all spawn from a single worker. You cannot use the regular worker from gunicorn. See the documentation for the command line.

  • #113 kamikaze said 2014-05-29T14:23:03Z

    How is it possible to run all this with uWSGI? Could you please provide an example config? Thanks.

    P.S. There are many problems reported for socket.io + uwsgi

  • #114 Miguel Grinberg said 2014-05-29T16:38:18Z

    @kamikaze: I believe uWSGI is not compatible with gevent-socketio. At least I have been unable to get these two to work together.

  • #115 Shane said 2014-05-30T16:14:10Z

    Miguel, Great work on the extension. Exploring this a bit more at the moment for some ideas. I want to set up a flask app that continually updates the user screen with broadcast messages after connection.

    I'm looking at starting a thread when the user connects first that generates new messages, and can 'emit' these back to connected clients continually. But running into issues with contexts / requests. Not sure if i'm approaching this the best way!

  • #116 Shane Lynn said 2014-05-30T16:29:30Z

    Miguel - got there just after i sent the comment (but after a few hours trying!) Discovered the socketio.emit() function in the documentation. When i got the namespace working properly, it all came together. Thanks!

  • #117 Miguel Grinberg said 2014-05-30T17:03:52Z

    @Shane: in case you need to see a working example, the app in the "example" directory on the github project shows how a background thread can emit messages to connected clients.

  • #118 Alex said 2014-05-31T10:21:55Z

    Hi,

    does it work with mod_wsgi?

    PS: I just started with websockets so this might be a stupid question.

  • #119 gloriajw said 2014-05-31T19:53:15Z

    Nice, clean implementation. Thank you for this.

  • #120 Miguel Grinberg said 2014-06-01T05:31:12Z

    @Alex: no, I believe mod_wsgi does not support websocket.

  • #121 Peter Illig said 2014-06-17T16:33:49Z

    Could you maybe detail how your library relates to gevent-socketio? What are its advantages/disadvantages?

    For example, gevent-socketio has issues when using multiple workers. How does your library fare in this scenario?

    Adding this comparison to the readme in the git might help the spread of your library. :)

  • #122 Miguel Grinberg said 2014-06-19T05:35:32Z

    @Peter: this extension wraps gevent-socketio, so any limitations you have found in that package will also be present here. The advantage is that this extension gives you a Flask friendly way to define your handlers using decorators.

  • #123 Arkind said 2014-06-21T12:10:34Z

    Hey,

    from "http://stackoverflow.com/questions/10058226/send-response-to-all-clients-except-sender-socket-io"

    Currently, flask-socketio support only the first one, not the second one. Right? // 1) sending to all clients, include sender io.sockets.emit('message', "this is a test");

    // 2) sending to all clients except sender socket.broadcast.emit('message', "this is a test");

    I and @Kevin, @beatle two of above users wants to support it.

    Is there way to support 2)?

  • #124 bradford said 2014-06-23T02:24:36Z

    I am trying to create my own smaller/basic version of the demo you created. I am having a bit of trouble. Specifically regarding 'socketio.virtsocket'. Could I get some help please? Thank you

  • #125 Miguel Grinberg said 2014-06-23T07:01:05Z

    @Arkind: sure it can be done. Please write an issue on GitHub so that I don't forget, I'll look into it when I have a moment.

Leave a Comment