1
- The Socket.IO Client
2
- ====================
1
+ The Socket.IO Clients
2
+ =====================
3
3
4
4
This package contains two Socket.IO clients:
5
5
6
- - The :func: ` socketio.Client ` class creates a client compatible with the
7
- standard Python library.
8
- - The :func: ` socketio.AsyncClient ` class creates a client compatible with
9
- the `` asyncio `` package.
6
+ - a "simple" client, which provides a straightforward API that is sufficient
7
+ for most applications
8
+ - an "event-driven" client, which provides access to all the features of the
9
+ Socket.IO protocol
10
10
11
- The methods in the two clients are the same, with the only difference that in
12
- the ``asyncio `` client most methods are implemented as coroutines.
11
+ Each of these clients comes in two variants: one for the standard Python
12
+ library, and another for asynchronous applications built with the ``asyncio ``
13
+ package.
13
14
14
15
Installation
15
16
------------
@@ -23,8 +24,174 @@ If instead you plan on using the ``asyncio`` client, then use this::
23
24
24
25
pip install "python-socketio[asyncio_client]"
25
26
27
+ Using the Simple Client
28
+ -----------------------
29
+
30
+ The advantage of the simple client is that it abstracts away the logic required
31
+ to maintain a Socket.IO connection. This client handles disconnections and
32
+ reconnections in a completely transparent way, without adding any complexity to
33
+ the application.
34
+
35
+ Creating a Client Instance
36
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
37
+
38
+ To instantiate a Socket.IO client, create an instance of the appropriate client
39
+ class::
40
+
41
+ import socketio
42
+
43
+ # standard Python
44
+ sio = socketio.SimpleClient()
45
+
46
+ # asyncio
47
+ sio = socketio.AsyncSimpleClient()
48
+
49
+ Connecting to a Server
50
+ ~~~~~~~~~~~~~~~~~~~~~~
51
+
52
+ The connection to a server is established by calling the ``connect() ``
53
+ method::
54
+
55
+ sio.connect('http://localhost:5000')
56
+
57
+ In the case of the ``asyncio `` client, the method is a coroutine::
58
+
59
+ await sio.connect('http://localhost:5000')
60
+
61
+ By default the client first connects to the server using the long-polling
62
+ transport, and then attempts to upgrade the connection to use WebSocket. To
63
+ connect directly using WebSocket, use the ``transports `` argument::
64
+
65
+ sio.connect('http://localhost:5000', transports=['websocket'])
66
+
67
+ Upon connection, the server assigns the client a unique session identifier.
68
+ The application can find this identifier in the ``sid `` attribute::
69
+
70
+ print('my sid is', sio.sid)
71
+
72
+ The Socket.IO transport that is used in the connection can be obtained from the
73
+ ``transport `` attribute::
74
+
75
+ print('my transport is', sio.transport)
76
+
77
+ The transport is given as a string, and can be either ``'websocket' `` or
78
+ ``'polling' ``.
79
+
80
+ TLS/SSL Support
81
+ ^^^^^^^^^^^^^^^
82
+
83
+ The client supports TLS/SSL connections. To enable it, use a ``https:// ``
84
+ connection URL::
85
+
86
+ sio.connect('https://example.com')
87
+
88
+ Or when using ``asyncio ``::
89
+
90
+ await sio.connect('https://example.com')
91
+
92
+ The client verifies server certificates by default. Consult the documentation
93
+ for the event-driven client for information on how to customize this behavior.
94
+
95
+ Emitting Events
96
+ ~~~~~~~~~~~~~~~
97
+
98
+ The client can emit an event to the server using the ``emit() `` method::
99
+
100
+ sio.emit('my message', {'foo': 'bar'})
101
+
102
+ Or in the case of ``asyncio ``, as a coroutine::
103
+
104
+ await sio.emit('my message', {'foo': 'bar'})
105
+
106
+ The arguments provided to the method are the name of the event to emit and the
107
+ optional data that is passed on to the server. The data can be of type ``str ``,
108
+ ``bytes ``, ``dict ``, ``list `` or ``tuple ``. When sending a ``list `` or a
109
+ ``tuple ``, the elements in it need to be of any allowed types except ``tuple ``.
110
+ When a tuple is used, the elements of the tuple will be passed as individual
111
+ arguments to the server-side event handler function.
112
+
113
+ Receiving Events
114
+ ~~~~~~~~~~~~~~~~
115
+
116
+ The client can wait for the server to emit an event with the ``receive() ``
117
+ method::
118
+
119
+ event = sio.receive()
120
+ print(f'received event: "{event[0]}" with arguments {event[1:]}')
121
+
122
+ When using ``asyncio ``, this method needs to be awaited::
123
+
124
+ event = await sio.receive()
125
+ print(f'received event: "{event[0]}" with arguments {event[1:]}')
126
+
127
+ The return value of ``receive() `` is a list. The first element of this list is
128
+ the event name, while the remaining elements are the arguments passed by the
129
+ server.
130
+
131
+ With the usage shown above, the ``receive() `` method will return only when an
132
+ event is received from the server. An optional timeout in seconds can be passed
133
+ to prevent the client from waiting forever::
134
+
135
+ from socketio.exceptions import TimeoutError
136
+
137
+ try:
138
+ event = sio.receive(timeout=5)
139
+ except TimeoutError:
140
+ print('timed out waiting for event')
141
+ else:
142
+ print('received event:', event)
143
+
144
+ Or with ``asyncio ``::
145
+
146
+ from socketio.exceptions import TimeoutError
147
+
148
+ try:
149
+ event = await sio.receive(timeout=5)
150
+ except TimeoutError:
151
+ print('timed out waiting for event')
152
+ else:
153
+ print('received event:', event)
154
+
155
+ Disconnecting from the Server
156
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
157
+
158
+ At any time the client can request to be disconnected from the server by
159
+ invoking the ``disconnect() `` method::
160
+
161
+ sio.disconnect()
162
+
163
+ For the ``asyncio `` client this is a coroutine::
164
+
165
+ await sio.disconnect()
166
+
167
+ Debugging and Troubleshooting
168
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
169
+
170
+ To help you debug issues, the client can be configured to output logs to the
171
+ terminal::
172
+
173
+ import socketio
174
+
175
+ # standard Python
176
+ sio = socketio.Client(logger=True, engineio_logger=True)
177
+
178
+ # asyncio
179
+ sio = socketio.AsyncClient(logger=True, engineio_logger=True)
180
+
181
+ The ``logger `` argument controls logging related to the Socket.IO protocol,
182
+ while ``engineio_logger `` controls logs that originate in the low-level
183
+ Engine.IO transport. These arguments can be set to ``True `` to output logs to
184
+ ``stderr ``, or to an object compatible with Python's ``logging `` package
185
+ where the logs should be emitted to. A value of ``False `` disables logging.
186
+
187
+ Logging can help identify the cause of connection problems, unexpected
188
+ disconnections and other issues.
189
+
190
+ Using the Event-Driven Client
191
+ -----------------------------
192
+
26
193
Creating a Client Instance
27
- --------------------------
194
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
28
195
29
196
To instantiate an Socket.IO client, simply create an instance of the
30
197
appropriate client class::
@@ -38,7 +205,7 @@ appropriate client class::
38
205
sio = socketio.AsyncClient()
39
206
40
207
Defining Event Handlers
41
- -----------------------
208
+ ~~~~~~~~~~~~~~~~~~~~~~~
42
209
43
210
The Socket.IO protocol is event based. When a server wants to communicate with
44
211
a client it *emits * an event. Each event has a name, and a list of
@@ -69,7 +236,7 @@ If the server includes arguments with an event, those are passed to the
69
236
handler function as arguments.
70
237
71
238
Catch-All Event Handlers
72
- ------------------------
239
+ ~~~~~~~~~~~~~~~~~~~~~~~~
73
240
74
241
A "catch-all" event handler is invoked for any events that do not have an
75
242
event handler. You can define a catch-all handler using ``'*' `` as event name::
@@ -88,9 +255,9 @@ A catch-all event handler receives the event name as a first argument. The
88
255
remaining arguments are the same as for a regular event handler.
89
256
90
257
Connect, Connect Error and Disconnect Event Handlers
91
- ----------------------------------------------------
258
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
92
259
93
- The ``connect ``, ``connect_error `` and ``disconnect `` events are special; they
260
+ The ``connect ``, ``connect_error `` and ``disconnect `` events are special; they
94
261
are invoked automatically when a client connects or disconnects from the
95
262
server::
96
263
@@ -122,7 +289,7 @@ The ``connect``, ``connect_error`` and ``disconnect`` events have to be
122
289
defined explicitly and are not invoked on a catch-all event handler.
123
290
124
291
Connecting to a Server
125
- ----------------------
292
+ ~~~~~~~~~~~~~~~~~~~~~~
126
293
127
294
The connection to a server is established by calling the ``connect() ``
128
295
method::
@@ -138,8 +305,16 @@ The application can find this identifier in the ``sid`` attribute::
138
305
139
306
print('my sid is', sio.sid)
140
307
308
+ The Socket.IO transport that is used in the connection can be obtained from the
309
+ ``transport `` attribute::
310
+
311
+ print('my transport is', sio.transport)
312
+
313
+ The transport is given as a string, and can be either ``'websocket' `` or
314
+ ``'polling' ``.
315
+
141
316
TLS/SSL Support
142
- ~~~~~~~~~~~~~~~
317
+ ^^^^^^^^^^^^^^^
143
318
144
319
The client supports TLS/SSL connections. To enable it, use a ``https:// ``
145
320
connection URL::
@@ -206,7 +381,7 @@ And for ``asyncio``::
206
381
await sio.connect('https://example.com')
207
382
208
383
Emitting Events
209
- ---------------
384
+ ~~~~~~~~~~~~~~~
210
385
211
386
The client can emit an event to the server using the ``emit() `` method::
212
387
@@ -216,18 +391,19 @@ Or in the case of ``asyncio``, as a coroutine::
216
391
217
392
await sio.emit('my message', {'foo': 'bar'})
218
393
219
- The single argument provided to the method is the data that is passed on
220
- to the server. The data can be of type ``str ``, ``bytes ``, ``dict ``,
221
- ``list `` or ``tuple ``. When sending a ``tuple ``, the elements in it need to
222
- be of any of the other four allowed types. The elements of the tuple will be
223
- passed as multiple arguments to the server-side event handler function.
394
+ The arguments provided to the method are the name of the event to emit and the
395
+ optional data that is passed on to the server. The data can be of type ``str ``,
396
+ ``bytes ``, ``dict ``, ``list `` or ``tuple ``. When sending a ``list `` or a
397
+ ``tuple ``, the elements in it need to be of any allowed types except ``tuple ``.
398
+ When a tuple is used, the elements of the tuple will be passed as individual
399
+ arguments to the server-side event handler function.
224
400
225
401
The ``emit() `` method can be invoked inside an event handler as a response
226
402
to a server event, or in any other part of the application, including in
227
403
background tasks.
228
404
229
405
Event Callbacks
230
- ---------------
406
+ ~~~~~~~~~~~~~~~
231
407
232
408
When a server emits an event to a client, it can optionally provide a
233
409
callback function, to be invoked as a way of acknowledgment that the server
@@ -249,7 +425,7 @@ the event, and any values returned by the server handler will be passed as
249
425
arguments to this function.
250
426
251
427
Namespaces
252
- ----------
428
+ ~~~~~~~~~~
253
429
254
430
The Socket.IO protocol supports multiple logical connections, all multiplexed
255
431
on the same physical connection. Clients can open multiple connections by
@@ -281,7 +457,7 @@ If the ``namespaces`` argument of the ``connect()`` call isn't given, any
281
457
namespaces used in event handlers are automatically connected.
282
458
283
459
Class-Based Namespaces
284
- ----------------------
460
+ ~~~~~~~~~~~~~~~~~~~~~~
285
461
286
462
As an alternative to the decorator-based event handlers, the event handlers
287
463
that belong to a namespace can be created as methods of a subclass of
@@ -332,7 +508,7 @@ decorator-based function handler, only the standalone function handler is
332
508
invoked.
333
509
334
510
Disconnecting from the Server
335
- -----------------------------
511
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
336
512
337
513
At any time the client can request to be disconnected from the server by
338
514
invoking the ``disconnect() `` method::
@@ -344,7 +520,7 @@ For the ``asyncio`` client this is a coroutine::
344
520
await sio.disconnect()
345
521
346
522
Managing Background Tasks
347
- -------------------------
523
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
348
524
349
525
When a client connection to the server is established, a few background
350
526
tasks will be spawned to keep the connection alive and handle incoming
@@ -398,7 +574,7 @@ The single argument passed to the method is the number of seconds to sleep
398
574
for.
399
575
400
576
Debugging and Troubleshooting
401
- -----------------------------
577
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
402
578
403
579
To help you debug issues, the client can be configured to output logs to the
404
580
terminal::
0 commit comments