0
# Synchronous Server
1
2
Full-featured Engine.IO server for synchronous Python applications. Provides event-driven real-time communication with support for multiple async models including threading, eventlet, and gevent.
3
4
## Capabilities
5
6
### Server Initialization
7
8
Create and configure a synchronous Engine.IO server with extensive customization options for transport protocols, timing parameters, and framework integration.
9
10
```python { .api }
11
class Server:
12
def __init__(
13
self,
14
async_mode=None,
15
ping_interval=25,
16
ping_timeout=20,
17
max_http_buffer_size=1000000,
18
allow_upgrades=True,
19
http_compression=True,
20
compression_threshold=1024,
21
cookie=None,
22
cors_allowed_origins=None,
23
cors_credentials=True,
24
logger=False,
25
json=None,
26
async_handlers=True,
27
monitor_clients=None,
28
transports=None,
29
**kwargs
30
):
31
"""
32
Initialize Engine.IO server.
33
34
Args:
35
async_mode (str, optional): Async model ('threading', 'eventlet', 'gevent', 'gevent_uwsgi')
36
ping_interval (int|tuple): Ping interval in seconds, default 25
37
ping_timeout (int): Ping timeout in seconds, default 20
38
max_http_buffer_size (int): Max message size in bytes, default 1,000,000
39
allow_upgrades (bool): Allow transport upgrades, default True
40
http_compression (bool): Enable HTTP compression, default True
41
compression_threshold (int): Compression threshold in bytes, default 1024
42
cookie (str|dict|None): Cookie configuration
43
cors_allowed_origins (str|list|callable): CORS allowed origins
44
cors_credentials (bool): Allow credentials in CORS, default True
45
logger (bool|Logger): Logging configuration, default False
46
json (module): Alternative JSON module
47
async_handlers (bool): Run handlers asynchronously, default True
48
monitor_clients (bool): Monitor client connections, default True
49
transports (list): Allowed transports, default ['polling', 'websocket']
50
"""
51
```
52
53
### Message Communication
54
55
Send messages and packets to connected clients with support for both individual and broadcast messaging.
56
57
```python { .api }
58
def send(self, sid, data):
59
"""
60
Send a message to a client.
61
62
Args:
63
sid (str): Session ID of the client
64
data (any): Message data to send
65
66
Raises:
67
SocketIsClosedError: If client socket is closed
68
"""
69
70
def send_packet(self, sid, pkt):
71
"""
72
Send a raw packet to a client.
73
74
Args:
75
sid (str): Session ID of the client
76
pkt (Packet): Raw packet object to send
77
78
Raises:
79
SocketIsClosedError: If client socket is closed
80
"""
81
```
82
83
### Session Management
84
85
Manage client sessions for storing user-specific data and maintaining state across connections.
86
87
```python { .api }
88
def get_session(self, sid):
89
"""
90
Return the user session for a client.
91
92
Args:
93
sid (str): Session ID of the client
94
95
Returns:
96
dict: User session data
97
98
Raises:
99
KeyError: If session does not exist
100
"""
101
102
def save_session(self, sid, session):
103
"""
104
Store the user session for a client.
105
106
Args:
107
sid (str): Session ID of the client
108
session (dict): Session data to store
109
"""
110
111
def session(self, sid):
112
"""
113
Return user session with context manager syntax.
114
115
Args:
116
sid (str): Session ID of the client
117
118
Returns:
119
ContextManager: Session context manager for automatic save
120
"""
121
```
122
123
Usage example:
124
125
```python
126
# Direct session management
127
session_data = eio.get_session(sid)
128
session_data['user_id'] = 123
129
eio.save_session(sid, session_data)
130
131
# Context manager approach
132
with eio.session(sid) as session:
133
session['user_id'] = 123
134
session['preferences'] = {'theme': 'dark'}
135
```
136
137
### Connection Management
138
139
Handle client connections and disconnections with fine-grained control over individual clients or all connections.
140
141
```python { .api }
142
def disconnect(self, sid=None):
143
"""
144
Disconnect a client or all clients.
145
146
Args:
147
sid (str, optional): Session ID to disconnect. If None, disconnects all clients
148
"""
149
150
def transport(self, sid):
151
"""
152
Return the transport name for a client.
153
154
Args:
155
sid (str): Session ID of the client
156
157
Returns:
158
str: Transport name ('polling' or 'websocket')
159
160
Raises:
161
KeyError: If client not found
162
"""
163
```
164
165
### Event Handling
166
167
Register event handlers for connection lifecycle and message processing with decorator or method syntax.
168
169
```python { .api }
170
def on(self, event, handler=None):
171
"""
172
Register an event handler.
173
174
Args:
175
event (str): Event name ('connect', 'message', 'disconnect')
176
handler (callable, optional): Event handler function
177
178
Returns:
179
callable: Decorator function if handler not provided
180
"""
181
```
182
183
Usage examples:
184
185
```python
186
# Decorator syntax
187
@eio.on('connect')
188
def on_connect(sid, environ):
189
print(f'Client {sid} connected')
190
191
@eio.on('message')
192
def on_message(sid, data):
193
print(f'Received: {data}')
194
eio.send(sid, f'Echo: {data}')
195
196
@eio.on('disconnect')
197
def on_disconnect(sid):
198
print(f'Client {sid} disconnected')
199
200
# Method syntax
201
def handle_connect(sid, environ):
202
print(f'Client {sid} connected')
203
204
eio.on('connect', handle_connect)
205
```
206
207
### WSGI Integration
208
209
Handle HTTP requests as a WSGI application for integration with web frameworks.
210
211
```python { .api }
212
def handle_request(self, environ, start_response):
213
"""
214
Handle an HTTP request (WSGI entry point).
215
216
Args:
217
environ (dict): WSGI environment dictionary
218
start_response (callable): WSGI start_response callable
219
220
Returns:
221
iterable: WSGI response iterable
222
"""
223
```
224
225
### Background Tasks
226
227
Manage background tasks using the appropriate async model for the server configuration.
228
229
```python { .api }
230
def start_background_task(self, target, *args, **kwargs):
231
"""
232
Start a background task.
233
234
Args:
235
target (callable): Task function to run
236
*args: Arguments for the task function
237
**kwargs: Keyword arguments for the task function
238
239
Returns:
240
Task object specific to the async mode
241
"""
242
243
def sleep(self, seconds=0):
244
"""
245
Sleep using the appropriate async model.
246
247
Args:
248
seconds (float): Sleep duration in seconds
249
"""
250
```
251
252
### Utility Methods
253
254
Utility functions for queue management, events, and session ID generation.
255
256
```python { .api }
257
def create_queue(self, *args, **kwargs):
258
"""
259
Create a queue object appropriate for the async mode.
260
261
Returns:
262
Queue object
263
"""
264
265
def get_queue_empty_exception(self):
266
"""
267
Return the queue empty exception for the async mode.
268
269
Returns:
270
Exception: Queue empty exception class
271
"""
272
273
def create_event(self, *args, **kwargs):
274
"""
275
Create an event object appropriate for the async mode.
276
277
Returns:
278
Event object
279
"""
280
281
def generate_id(self):
282
"""
283
Generate a unique session ID.
284
285
Returns:
286
str: Unique session identifier
287
"""
288
289
def shutdown(self):
290
"""
291
Stop all background tasks and clean up resources.
292
"""
293
```
294
295
## Server Lifecycle Events
296
297
The server emits the following events during client interactions:
298
299
- **connect**: Fired when a client establishes a connection
300
- Handler signature: `(sid: str, environ: dict) -> None`
301
- `sid`: Session ID of the connecting client
302
- `environ`: WSGI environment dictionary
303
304
- **message**: Fired when a message is received from a client
305
- Handler signature: `(sid: str, data: any) -> None`
306
- `sid`: Session ID of the sending client
307
- `data`: Message data received from client
308
309
- **disconnect**: Fired when a client disconnects
310
- Handler signature: `(sid: str) -> None`
311
- `sid`: Session ID of the disconnecting client
312
313
## Disconnection Reasons
314
315
```python { .api }
316
class Server.reason:
317
SERVER_DISCONNECT = 'server disconnect'
318
CLIENT_DISCONNECT = 'client disconnect'
319
PING_TIMEOUT = 'ping timeout'
320
TRANSPORT_CLOSE = 'transport close'
321
TRANSPORT_ERROR = 'transport error'
322
```
323
324
## Configuration Constants
325
326
```python { .api }
327
# Available compression methods
328
compression_methods = ['gzip', 'deflate']
329
330
# Valid event names
331
event_names = ['connect', 'disconnect', 'message']
332
333
# Supported transport protocols
334
valid_transports = ['polling', 'websocket']
335
```
336
337
## Error Handling
338
339
The server may raise the following exceptions during operation:
340
341
- `EngineIOError`: Base exception for all Engine.IO errors
342
- `SocketIsClosedError`: When attempting to send to a closed socket
343
- `ContentTooLongError`: When message size exceeds buffer limits
344
- `ConnectionError`: When connection fails or is lost unexpectedly