0
# Synchronous Client
1
2
Engine.IO client for connecting to servers from synchronous Python applications. Provides automatic reconnection, transport fallback support, and event-driven communication patterns.
3
4
## Capabilities
5
6
### Client Initialization
7
8
Create and configure a synchronous Engine.IO client with customization options for timeouts, SSL verification, and transport protocols.
9
10
```python { .api }
11
class Client:
12
def __init__(
13
self,
14
logger=False,
15
json=None,
16
request_timeout=5,
17
http_session=None,
18
ssl_verify=True,
19
handle_sigint=True,
20
websocket_extra_options=None,
21
timestamp_requests=True
22
):
23
"""
24
Initialize Engine.IO client.
25
26
Args:
27
logger (bool|Logger): Logging configuration, default False
28
json (module): Alternative JSON module
29
request_timeout (int): Request timeout in seconds, default 5
30
http_session (requests.Session): HTTP session object for requests
31
ssl_verify (bool): Verify SSL certificates, default True
32
handle_sigint (bool): Handle SIGINT automatically, default True
33
websocket_extra_options (dict): Extra WebSocket client options
34
timestamp_requests (bool): Add timestamps to requests, default True
35
"""
36
```
37
38
### Connection Management
39
40
Establish connections to Engine.IO servers with support for custom headers, transport selection, and endpoint configuration.
41
42
```python { .api }
43
def connect(self, url, headers=None, transports=None, engineio_path='engine.io'):
44
"""
45
Connect to an Engine.IO server.
46
47
Args:
48
url (str): Server URL (e.g., 'http://localhost:5000')
49
headers (dict, optional): Additional HTTP headers for connection
50
transports (list, optional): Allowed transports ['polling', 'websocket']
51
engineio_path (str): Engine.IO endpoint path, default 'engine.io'
52
53
Raises:
54
ConnectionError: If connection fails
55
ValueError: If URL is invalid or transports unsupported
56
"""
57
58
def wait(self):
59
"""
60
Wait until the connection ends.
61
62
This method blocks the current thread until the client disconnects
63
or the connection is lost.
64
"""
65
66
def disconnect(self, abort=False, reason=None):
67
"""
68
Disconnect from the server.
69
70
Args:
71
abort (bool): Abort connection immediately without graceful shutdown
72
reason (str, optional): Reason for disconnection
73
"""
74
```
75
76
### Message Communication
77
78
Send messages to the server and receive responses through the event system.
79
80
```python { .api }
81
def send(self, data):
82
"""
83
Send a message to the server.
84
85
Args:
86
data (any): Message data to send (will be JSON-serialized)
87
88
Raises:
89
SocketIsClosedError: If not connected to server
90
"""
91
```
92
93
### Event Handling
94
95
Register event handlers for connection lifecycle and message processing.
96
97
```python { .api }
98
def on(self, event, handler=None):
99
"""
100
Register an event handler.
101
102
Args:
103
event (str): Event name ('connect', 'message', 'disconnect')
104
handler (callable, optional): Event handler function
105
106
Returns:
107
callable: Decorator function if handler not provided
108
"""
109
```
110
111
Usage examples:
112
113
```python
114
# Decorator syntax
115
@client.on('connect')
116
def on_connect():
117
print('Connected to server')
118
client.send('Hello Server!')
119
120
@client.on('message')
121
def on_message(data):
122
print(f'Received from server: {data}')
123
124
@client.on('disconnect')
125
def on_disconnect():
126
print('Disconnected from server')
127
128
# Method syntax
129
def handle_message(data):
130
print(f'Message: {data}')
131
132
client.on('message', handle_message)
133
```
134
135
### Transport Information
136
137
Query the current transport being used for the connection.
138
139
```python { .api }
140
def transport(self):
141
"""
142
Return the current transport name.
143
144
Returns:
145
str: Transport name ('polling' or 'websocket')
146
147
Raises:
148
ValueError: If not connected
149
"""
150
```
151
152
### Background Tasks
153
154
Manage background tasks using the appropriate threading model.
155
156
```python { .api }
157
def start_background_task(self, target, *args, **kwargs):
158
"""
159
Start a background task.
160
161
Args:
162
target (callable): Task function to run
163
*args: Arguments for the task function
164
**kwargs: Keyword arguments for the task function
165
166
Returns:
167
Thread: Thread object for the background task
168
"""
169
170
def sleep(self, seconds=0):
171
"""
172
Sleep for the requested time.
173
174
Args:
175
seconds (float): Sleep duration in seconds
176
"""
177
```
178
179
### Utility Methods
180
181
Utility functions for queue management, events, and threading primitives.
182
183
```python { .api }
184
def create_queue(self, *args, **kwargs):
185
"""
186
Create a queue object appropriate for threading.
187
188
Returns:
189
queue.Queue: Thread-safe queue object
190
"""
191
192
def get_queue_empty_exception(self):
193
"""
194
Return the queue empty exception for threading.
195
196
Returns:
197
queue.Empty: Queue empty exception class
198
"""
199
200
def create_event(self, *args, **kwargs):
201
"""
202
Create an event object appropriate for threading.
203
204
Returns:
205
threading.Event: Threading event object
206
"""
207
```
208
209
## Client Lifecycle Events
210
211
The client emits the following events during server interactions:
212
213
- **connect**: Fired when connection to server is established
214
- Handler signature: `() -> None`
215
- Called after successful connection handshake
216
217
- **message**: Fired when a message is received from the server
218
- Handler signature: `(data: any) -> None`
219
- `data`: Message data received from server
220
221
- **disconnect**: Fired when disconnected from the server
222
- Handler signature: `() -> None`
223
- Called for both graceful and unexpected disconnections
224
225
## Connection Examples
226
227
### Basic Connection
228
229
```python
230
import engineio
231
232
client = engineio.Client()
233
234
@client.on('connect')
235
def on_connect():
236
print('Connected!')
237
client.send('Hello from client')
238
239
@client.on('message')
240
def on_message(data):
241
print(f'Server says: {data}')
242
243
client.connect('http://localhost:5000')
244
client.wait()
245
```
246
247
### Connection with Custom Headers
248
249
```python
250
import engineio
251
252
client = engineio.Client()
253
254
headers = {
255
'Authorization': 'Bearer token123',
256
'User-Agent': 'MyApp/1.0'
257
}
258
259
client.connect('https://api.example.com', headers=headers)
260
```
261
262
### Connection with SSL Options
263
264
```python
265
import engineio
266
import requests
267
268
# Create custom HTTP session with SSL settings
269
session = requests.Session()
270
session.verify = '/path/to/ca-bundle.crt'
271
272
client = engineio.Client(
273
http_session=session,
274
ssl_verify=True,
275
request_timeout=10
276
)
277
278
client.connect('https://secure-server.com')
279
```
280
281
### Transport Selection
282
283
```python
284
import engineio
285
286
# Only use WebSocket transport
287
client = engineio.Client()
288
client.connect('ws://localhost:5000', transports=['websocket'])
289
290
# Only use polling transport
291
client.connect('http://localhost:5000', transports=['polling'])
292
```
293
294
## Disconnection Reasons
295
296
```python { .api }
297
class Client.reason:
298
CLIENT_DISCONNECT = 'client disconnect'
299
SERVER_DISCONNECT = 'server disconnect'
300
TRANSPORT_ERROR = 'transport error'
301
```
302
303
## Configuration Constants
304
305
```python { .api }
306
# Valid event names
307
event_names = ['connect', 'disconnect', 'message']
308
```
309
310
## Error Handling
311
312
The client may raise the following exceptions during operation:
313
314
- `ConnectionError`: When connection to server fails or is lost
315
- `SocketIsClosedError`: When attempting to send while not connected
316
- `ValueError`: When invalid parameters are provided
317
- `TimeoutError`: When requests exceed the configured timeout
318
319
## Advanced Usage
320
321
### Automatic Reconnection
322
323
```python
324
import engineio
325
import time
326
327
client = engineio.Client()
328
329
@client.on('connect')
330
def on_connect():
331
print('Connected to server')
332
333
@client.on('disconnect')
334
def on_disconnect():
335
print('Disconnected, attempting to reconnect...')
336
time.sleep(5)
337
try:
338
client.connect('http://localhost:5000')
339
except Exception as e:
340
print(f'Reconnection failed: {e}')
341
342
client.connect('http://localhost:5000')
343
client.wait()
344
```
345
346
### Custom JSON Serialization
347
348
```python
349
import engineio
350
import ujson # Ultra-fast JSON library
351
352
client = engineio.Client(json=ujson)
353
client.connect('http://localhost:5000')
354
```