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, to get the socketserver command

  • In your, add:

    from flask_socketio import SocketIO
    socketio = SocketIO(app)

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

  • In your main file,, 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 before any of your JavaScript that uses it:

    <script src=""></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

Server Programming

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

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

def socket_message(msg):
    # in here, 'msg' is a string

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'});