Python Socket.IO
python-socketio is a comprehensive Python implementation of the Socket.IO real-time communication protocol, offering both server and client functionalities. It enables low-latency, bidirectional, and event-based communication between clients (often web browsers) and a Python server. The library is actively maintained with frequent releases, providing compatibility with various asynchronous frameworks and web servers.
Warnings
- breaking Protocol compatibility is critical: python-socketio v5.x is compatible with JavaScript Socket.IO 3.x and 4.x. Mixing incompatible versions will lead to connection errors or unexpected behavior.
- gotcha Missing or incorrect `cors_allowed_origins` can cause connection refusal errors for browser-based clients due to Cross-Origin Resource Sharing (CORS) policies.
- gotcha Using `Gunicorn` with multiple worker processes for `python-socketio` requires sticky sessions (load balancer must route a client to the same worker) and forcing WebSocket-only transport. Long-polling is incompatible with Gunicorn's default load balancing across workers.
- deprecated The `eventlet` asynchronous framework, while supported, is no longer actively maintained. Using `gevent` or `asyncio` is generally recommended for new projects for better long-term support and performance.
- breaking In Socket.IO v5 protocol (python-socketio 5.x), the default namespace ('/') is not automatically connected. Each namespace connection, including the default, now has its own unique session ID (`sid`), distinct from the Engine.IO `sid`.
Install
-
pip install python-socketio -
pip install "python-socketio[client]" -
pip install "python-socketio[asyncio_client]"
Imports
- Server
import socketio sio = socketio.Server()
- AsyncServer
import socketio sio = socketio.AsyncServer()
- Client
import socketio sio = socketio.Client()
- AsyncClient
import socketio sio = socketio.AsyncClient()
- WSGIApp
import socketio app = socketio.WSGIApp(sio)
- ASGIApp
import socketio app = socketio.ASGIApp(sio)
Quickstart
import socketio
import eventlet
sio = socketio.Server(cors_allowed_origins="*")
app = socketio.WSGIApp(sio, static_files={
'/': {'content_type': 'text/html', 'filename': 'index.html'}
})
@sio.event
def connect(sid, environ):
print('connect ', sid)
@sio.event
def my_message(sid, data):
print('message ', data)
sio.emit('my response', {'data': data}, room=sid)
@sio.event
def disconnect(sid):
print('disconnect ', sid)
if __name__ == '__main__':
# index.html for testing
with open('index.html', 'w') as f:
f.write('''
<!DOCTYPE html>
<html>
<head>
<title>Socket.IO Test</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
</head>
<body>
<h1>Socket.IO Test</h1>
<script type="text/javascript">
var socket = io();
socket.on('connect', function() {
console.log('Connected!');
socket.emit('my_message', 'Hello from browser!');
});
socket.on('my response', function(data) {
console.log('Received:', data);
});
socket.on('disconnect', function() {
console.log('Disconnected!');
});
</script>
</body>
</html>
''')
print("Starting server on http://localhost:5000")
eventlet.wsgi.server(eventlet.listen(('', 5000)), app)