Run a Socket.io Python application

This article shows how to use Socket.io with Python, running a simple python-socketio application on a Uwsgi server.

Application

The following application shows basic implementation to handle ws:// connections from a socket client.

Python Socket.io version

The version of python-socketio is critical to ensure protocol compatibility with the client libraries.
Make sure to use the following pip package versions:

requirements.txt
1
2
3
python-engineio==3.13.2
python-socketio==4.6.0
gevent==1.5.0

Install

Make sure to run inside a virtual environment or rather inside a Dockerfile, if you plan to run the application inside a container.

install dependencies
1
pip install python-engineio==3.13.2 python-socketio==4.6.0 gevent==1.5.0

Server

The uwsgi server is a great option to run Python applications, it has a vast set of configuration options and can be easily built with customized extensions.

Customize uwsgi server

For example to build with ssl support by default, use the following command:

build uwsgi with ssl
1
2
3
4
CFLAGS="-I/usr/local/opt/openssl/include" \
LDFLAGS="-L/usr/local/opt/openssl/lib" \
UWSGI_PROFILE_OVERRIDE=ssl=true \
pip3 install uwsgi -I --no-cache-dir

Run uwsgi server

The following command can be used to run the previous application (file main.py) on port 3333:

run uwsgi
1
2
3
4
5
uwsgi -w main:app\
--http11-socket 127.0.0.1:3333\
--enable-threads\
--threads 4\
--logformat '%(addr) - %(user) [%(ltime)] "%(method) %(uri) %(proto)" %(status) %(size) "%(referer)" "%(uagent)"'

Client

Any 1.x version has been tested to be compatible with the python-socketio server.
This example makes use of the Socket.io Release 1.7.0.
You can have a look at all the available versions of the Socket.io javascript client here.

In case you decide to use different versions, mind to check the compatibility of the client, to match the server protocol version of the python-socketio version of your choose.

The following code implements a minimal client using Socket.io 1.7.0

References: