0
# Python Socket.IO
1
2
A comprehensive Python implementation of the Socket.IO realtime communication protocol, providing both synchronous and asynchronous clients and servers. Socket.IO enables bidirectional real-time communication between web clients and servers through WebSocket connections with fallback support for polling transport.
3
4
## Package Information
5
6
- **Package Name**: python-socketio
7
- **Language**: Python (>=3.8)
8
- **Installation**: `pip install python-socketio`
9
- **Version**: 5.13.0
10
11
## Core Imports
12
13
```python
14
import socketio
15
```
16
17
Common specific imports:
18
19
```python
20
from socketio import Server, AsyncServer, Client, AsyncClient
21
from socketio import SimpleClient, AsyncSimpleClient
22
from socketio import Namespace, AsyncNamespace
23
from socketio import WSGIApp, ASGIApp
24
```
25
26
## Basic Usage
27
28
### Simple Server
29
30
```python
31
import socketio
32
33
# Create a Socket.IO server
34
sio = socketio.Server()
35
36
@sio.event
37
def connect(sid, environ):
38
print(f'Client {sid} connected')
39
40
@sio.event
41
def disconnect(sid):
42
print(f'Client {sid} disconnected')
43
44
@sio.event
45
def message(sid, data):
46
# Echo the message back to the client
47
sio.emit('response', {'echo': data}, room=sid)
48
49
# WSGI application
50
app = socketio.WSGIApp(sio)
51
```
52
53
### Simple Client
54
55
```python
56
import socketio
57
58
# Create a Socket.IO client
59
sio = socketio.Client()
60
61
@sio.event
62
def connect():
63
print('Connected to server')
64
sio.emit('message', {'hello': 'world'})
65
66
@sio.event
67
def response(data):
68
print(f'Received: {data}')
69
70
# Connect to server
71
sio.connect('http://localhost:5000')
72
```
73
74
### Asynchronous Server
75
76
```python
77
import socketio
78
79
# Create an async Socket.IO server
80
sio = socketio.AsyncServer()
81
82
@sio.event
83
async def connect(sid, environ):
84
print(f'Client {sid} connected')
85
86
@sio.event
87
async def message(sid, data):
88
await sio.emit('response', {'echo': data}, room=sid)
89
90
# ASGI application
91
app = socketio.ASGIApp(sio)
92
```
93
94
## Architecture
95
96
The python-socketio library provides a hierarchical architecture supporting both synchronous and asynchronous operation patterns:
97
98
- **Client/Server Classes**: Core communication endpoints (sync and async variants)
99
- **Manager Classes**: Handle client connections and message routing, with support for scaling across multiple processes using Redis, Kafka, RabbitMQ, and ZeroMQ
100
- **Namespace Classes**: Organize communication into logical groups with class-based event handlers
101
- **Middleware Classes**: Integration adapters for web frameworks (WSGI, ASGI, Tornado)
102
- **Transport Support**: Automatic WebSocket with polling fallback through Engine.IO integration
103
104
This design enables everything from simple single-process applications to horizontally-scaled real-time systems while maintaining compatibility with the JavaScript Socket.IO ecosystem.
105
106
## Capabilities
107
108
### Client Classes
109
110
Socket.IO client implementations for connecting to servers, supporting both simple blocking operations and full-featured event-driven communication with automatic reconnection and namespace support.
111
112
```python { .api }
113
class SimpleClient:
114
def connect(self, url, **kwargs): ...
115
def emit(self, event, data=None): ...
116
def call(self, event, data=None, timeout=60): ...
117
def receive(self, timeout=None): ...
118
def disconnect(self): ...
119
120
class Client:
121
def connect(self, url, **kwargs): ...
122
def emit(self, event, data=None, namespace=None, callback=None): ...
123
def call(self, event, data=None, namespace=None, timeout=60): ...
124
def wait(self): ...
125
def disconnect(self): ...
126
127
class AsyncSimpleClient:
128
async def connect(self, url, **kwargs): ...
129
async def emit(self, event, data=None): ...
130
async def call(self, event, data=None, timeout=60): ...
131
async def receive(self, timeout=None): ...
132
async def disconnect(self): ...
133
134
class AsyncClient:
135
async def connect(self, url, **kwargs): ...
136
async def emit(self, event, data=None, namespace=None, callback=None): ...
137
async def call(self, event, data=None, namespace=None, timeout=60): ...
138
async def wait(self): ...
139
async def disconnect(self): ...
140
```
141
142
[Client Classes](./clients.md)
143
144
### Server Classes
145
146
Socket.IO server implementations for handling multiple client connections, supporting event-driven architecture, room management, session handling, and client manager integration for horizontal scaling.
147
148
```python { .api }
149
class Server:
150
def emit(self, event, data=None, to=None, room=None, skip_sid=None, namespace=None, callback=None): ...
151
def send(self, data, to=None, room=None, skip_sid=None, namespace=None, callback=None): ...
152
def call(self, event, data=None, to=None, sid=None, namespace=None, timeout=60): ...
153
def enter_room(self, sid, room, namespace=None): ...
154
def leave_room(self, sid, room, namespace=None): ...
155
def close_room(self, room, namespace=None): ...
156
def get_session(self, sid, namespace=None): ...
157
def save_session(self, sid, session, namespace=None): ...
158
def disconnect(self, sid, namespace=None): ...
159
160
class AsyncServer:
161
async def emit(self, event, data=None, to=None, room=None, skip_sid=None, namespace=None, callback=None): ...
162
async def send(self, data, to=None, room=None, skip_sid=None, namespace=None, callback=None): ...
163
async def call(self, event, data=None, to=None, sid=None, namespace=None, timeout=60): ...
164
async def enter_room(self, sid, room, namespace=None): ...
165
async def leave_room(self, sid, room, namespace=None): ...
166
async def close_room(self, room, namespace=None): ...
167
async def get_session(self, sid, namespace=None): ...
168
async def save_session(self, sid, session, namespace=None): ...
169
async def disconnect(self, sid, namespace=None): ...
170
```
171
172
[Server Classes](./servers.md)
173
174
### Namespace Classes
175
176
Class-based event handlers that organize Socket.IO communication into logical namespaces, supporting inheritance and method-based event handling for both client and server scenarios.
177
178
```python { .api }
179
class Namespace:
180
def trigger_event(self, event, *args): ...
181
def emit(self, event, data=None, to=None, room=None, skip_sid=None, namespace=None, callback=None): ...
182
def send(self, data, to=None, room=None, skip_sid=None, namespace=None, callback=None): ...
183
def call(self, event, data=None, to=None, sid=None, namespace=None, timeout=60): ...
184
def enter_room(self, sid, room, namespace=None): ...
185
def leave_room(self, sid, room, namespace=None): ...
186
def disconnect(self, sid, namespace=None): ...
187
188
class ClientNamespace:
189
def trigger_event(self, event, *args): ...
190
def emit(self, event, data=None, namespace=None, callback=None): ...
191
def send(self, data, namespace=None, callback=None): ...
192
def call(self, event, data=None, namespace=None, timeout=60): ...
193
def disconnect(self): ...
194
195
class AsyncNamespace:
196
async def trigger_event(self, event, *args): ...
197
async def emit(self, event, data=None, to=None, room=None, skip_sid=None, namespace=None, callback=None): ...
198
async def send(self, data, to=None, room=None, skip_sid=None, namespace=None, callback=None): ...
199
async def call(self, event, data=None, to=None, sid=None, namespace=None, timeout=60): ...
200
async def enter_room(self, sid, room, namespace=None): ...
201
async def leave_room(self, sid, room, namespace=None): ...
202
async def disconnect(self, sid, namespace=None): ...
203
204
class AsyncClientNamespace:
205
async def trigger_event(self, event, *args): ...
206
async def emit(self, event, data=None, namespace=None, callback=None): ...
207
async def send(self, data, namespace=None, callback=None): ...
208
async def call(self, event, data=None, namespace=None, timeout=60): ...
209
async def disconnect(self): ...
210
```
211
212
[Namespace Classes](./namespaces.md)
213
214
### Manager Classes
215
216
Client connection managers that handle message routing, room membership, and horizontal scaling through pub/sub messaging systems like Redis, Kafka, RabbitMQ, and ZeroMQ.
217
218
```python { .api }
219
class Manager:
220
def emit(self, event, data, namespace, room=None, skip_sid=None, callback=None, **kwargs): ...
221
def can_disconnect(self, sid, namespace): ...
222
def disconnect(self, sid, namespace=None): ...
223
def enter_room(self, sid, namespace, room, eio_sid=None): ...
224
def leave_room(self, sid, namespace, room): ...
225
def close_room(self, room, namespace): ...
226
227
class PubSubManager(Manager):
228
def __init__(self, channel='socketio', write_only=False, logger=None): ...
229
230
class RedisManager(PubSubManager):
231
def __init__(self, url='redis://localhost:6379/0', channel='socketio', write_only=False, logger=None, redis_options=None): ...
232
233
class KafkaManager(PubSubManager):
234
def __init__(self, url='kafka://localhost:9092', channel='socketio', write_only=False, logger=None): ...
235
```
236
237
[Manager Classes](./managers.md)
238
239
### Web Framework Integration
240
241
Middleware classes for integrating Socket.IO servers with popular Python web frameworks, supporting both WSGI and ASGI patterns with static file serving and flexible routing.
242
243
```python { .api }
244
class WSGIApp:
245
def __init__(self, socketio_app, wsgi_app=None, static_files=None, socketio_path='socket.io'): ...
246
247
class ASGIApp:
248
def __init__(self, socketio_server, other_asgi_app=None, static_files=None, socketio_path='socket.io', on_startup=None, on_shutdown=None): ...
249
250
def get_tornado_handler(socketio_server):
251
"""Get Tornado request handler for Socket.IO server.
252
253
Returns:
254
Tornado handler class for Socket.IO integration
255
"""
256
```
257
258
[Web Framework Integration](./integration.md)
259
260
### Exception Handling
261
262
Comprehensive exception hierarchy for handling Socket.IO-specific errors including connection failures, timeouts, namespace issues, and disconnection scenarios.
263
264
```python { .api }
265
class SocketIOError(Exception): ...
266
267
class ConnectionError(SocketIOError): ...
268
269
class ConnectionRefusedError(ConnectionError):
270
def __init__(self, *args): ...
271
272
class TimeoutError(SocketIOError): ...
273
274
class BadNamespaceError(SocketIOError): ...
275
276
class DisconnectedError(SocketIOError): ...
277
```
278
279
[Exception Handling](./exceptions.md)