Skip to content

Commit 55d6310

Browse files
Simplified client (#1237)
1 parent 7208ec0 commit 55d6310

30 files changed

+1208
-73
lines changed

docs/api.rst

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,18 @@ API Reference
66

77
.. module:: socketio
88

9+
``SimpleClient`` class
10+
----------------------
11+
12+
.. autoclass:: SimpleClient
13+
:members:
14+
15+
``AsyncSimpleClient`` class
16+
---------------------------
17+
18+
.. autoclass:: AsyncSimpleClient
19+
:members:
20+
921
``Client`` class
1022
----------------
1123

docs/client.rst

Lines changed: 203 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,16 @@
1-
The Socket.IO Client
2-
====================
1+
The Socket.IO Clients
2+
=====================
33

44
This package contains two Socket.IO clients:
55

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
1010

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.
1314

1415
Installation
1516
------------
@@ -23,8 +24,174 @@ If instead you plan on using the ``asyncio`` client, then use this::
2324

2425
pip install "python-socketio[asyncio_client]"
2526

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+
26193
Creating a Client Instance
27-
--------------------------
194+
~~~~~~~~~~~~~~~~~~~~~~~~~~
28195

29196
To instantiate an Socket.IO client, simply create an instance of the
30197
appropriate client class::
@@ -38,7 +205,7 @@ appropriate client class::
38205
sio = socketio.AsyncClient()
39206

40207
Defining Event Handlers
41-
-----------------------
208+
~~~~~~~~~~~~~~~~~~~~~~~
42209

43210
The Socket.IO protocol is event based. When a server wants to communicate with
44211
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
69236
handler function as arguments.
70237

71238
Catch-All Event Handlers
72-
------------------------
239+
~~~~~~~~~~~~~~~~~~~~~~~~
73240

74241
A "catch-all" event handler is invoked for any events that do not have an
75242
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
88255
remaining arguments are the same as for a regular event handler.
89256

90257
Connect, Connect Error and Disconnect Event Handlers
91-
----------------------------------------------------
258+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
92259

93-
The ``connect``, ``connect_error`` and ``disconnect`` events are special; they
260+
The ``connect``, ``connect_error`` and ``disconnect`` events are special; they
94261
are invoked automatically when a client connects or disconnects from the
95262
server::
96263

@@ -122,7 +289,7 @@ The ``connect``, ``connect_error`` and ``disconnect`` events have to be
122289
defined explicitly and are not invoked on a catch-all event handler.
123290

124291
Connecting to a Server
125-
----------------------
292+
~~~~~~~~~~~~~~~~~~~~~~
126293

127294
The connection to a server is established by calling the ``connect()``
128295
method::
@@ -138,8 +305,16 @@ The application can find this identifier in the ``sid`` attribute::
138305

139306
print('my sid is', sio.sid)
140307

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+
141316
TLS/SSL Support
142-
~~~~~~~~~~~~~~~
317+
^^^^^^^^^^^^^^^
143318

144319
The client supports TLS/SSL connections. To enable it, use a ``https://``
145320
connection URL::
@@ -206,7 +381,7 @@ And for ``asyncio``::
206381
await sio.connect('https://example.com')
207382

208383
Emitting Events
209-
---------------
384+
~~~~~~~~~~~~~~~
210385

211386
The client can emit an event to the server using the ``emit()`` method::
212387

@@ -216,18 +391,19 @@ Or in the case of ``asyncio``, as a coroutine::
216391

217392
await sio.emit('my message', {'foo': 'bar'})
218393

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.
224400

225401
The ``emit()`` method can be invoked inside an event handler as a response
226402
to a server event, or in any other part of the application, including in
227403
background tasks.
228404

229405
Event Callbacks
230-
---------------
406+
~~~~~~~~~~~~~~~
231407

232408
When a server emits an event to a client, it can optionally provide a
233409
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
249425
arguments to this function.
250426

251427
Namespaces
252-
----------
428+
~~~~~~~~~~
253429

254430
The Socket.IO protocol supports multiple logical connections, all multiplexed
255431
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
281457
namespaces used in event handlers are automatically connected.
282458

283459
Class-Based Namespaces
284-
----------------------
460+
~~~~~~~~~~~~~~~~~~~~~~
285461

286462
As an alternative to the decorator-based event handlers, the event handlers
287463
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
332508
invoked.
333509

334510
Disconnecting from the Server
335-
-----------------------------
511+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
336512

337513
At any time the client can request to be disconnected from the server by
338514
invoking the ``disconnect()`` method::
@@ -344,7 +520,7 @@ For the ``asyncio`` client this is a coroutine::
344520
await sio.disconnect()
345521

346522
Managing Background Tasks
347-
-------------------------
523+
~~~~~~~~~~~~~~~~~~~~~~~~~
348524

349525
When a client connection to the server is established, a few background
350526
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
398574
for.
399575

400576
Debugging and Troubleshooting
401-
-----------------------------
577+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
402578

403579
To help you debug issues, the client can be configured to output logs to the
404580
terminal::

docs/conf.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,8 @@
4242
'sphinx.ext.autodoc',
4343
]
4444

45+
autodoc_member_order = 'bysource'
46+
4547
# Add any paths that contain templates here, relative to this directory.
4648
templates_path = ['_templates']
4749

examples/README.rst

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,5 +2,5 @@ Socket.IO Examples
22
==================
33

44
This directory contains several example Socket.IO applications. Look in the
5-
`server` directory for Socket.IO servers, and in the `client` directory for
6-
Socket.IO clients.
5+
`server` directory for Socket.IO servers, and in the `client` and
6+
`simple-client` directories for Socket.IO clients.

examples/client/README.rst

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,13 @@ Socket.IO Client Examples
44
This directory contains several example Socket.IO client applications,
55
organized by directory:
66

7-
threads
8-
-------
7+
sync
8+
----
99

1010
Examples that use standard Python thread concurrency.
1111

12-
asyncio
13-
-------
12+
async
13+
-----
1414

1515
Examples that use Python's `asyncio` package for concurrency.
1616

0 commit comments

Comments
 (0)