Working with SocketIO

This page provides some info & tips for working with SocketIO.

Software Requirements

To use SocketIO, you need the following:

  • The flask-socketio package installed in your virtual environment

  • At least version 5 manage.py, to get the socketserver command

  • In your init.py, add:

    from flask_socketio import SocketIO
    socketio = SocketIO(app)
    

    The name socketio is important, as it is what manage.py expects.

  • In your main file, app.py, import socketio from init in addition to app.

  • If you are developing on Mac or Linux, it's a good idea to install the Python eventlet package in your virtual environment, to get real WebSocket support.

  • In your HTML file, load socket.io before any of your JavaScript that uses it:

    <script src="https://cdn.jsdelivr.net/socket.io-client/1.3.2/socket.io.min.js"></script>
    

Running the Server

You cannot use runserver to run a Flask app that uses SocketIO. If you do, you'll experience lots of hangs and very slow performance, and most things won't even work.

Instead, use socketserver, provided by version 5 of manage.py.

Server Programming

In your server code, you can respond to SocketIO events:

from init import app, socketio
from flask_socketio import send, emit

@socketio.on('message')
def socket_message(msg):
    # in here, 'msg' is a string

@socketio.on('json')
def socket_message(data):
    # in here, 'data' is a Python object parsed from JSON

You can emit events with emit: emit('hai', hai_payload).

See the Hai example for an example of using SocketIO rooms to manage notifications to a group of connections.

Client Programming

In the client, set up a SocketIO object:

var socket = io();

Then you can respond to events:

socket.on('message', function(msg) {
    console.log('received message %s', msg);
})

You can send messages:

socket.emit('json', {id: 30, value: 'wombats are cute'});