0
# Asyncio Client Operations
1
2
High-level asyncio-based WebSocket client functionality for connecting to WebSocket servers, managing connection lifecycle, and handling message communication using Python's async/await syntax.
3
4
## Capabilities
5
6
### Connection Functions
7
8
Create WebSocket client connections with support for various protocols, authentication, compression, and connection options.
9
10
```python { .api }
11
async def connect(
12
uri: str,
13
*,
14
additional_headers: HeadersLike = None,
15
user_agent_header: str = None,
16
compression: str = "deflate",
17
logger: LoggerLike = None,
18
subprotocols: List[Subprotocol] = None,
19
extra_headers: HeadersLike = None,
20
open_timeout: float = 10,
21
close_timeout: float = 10,
22
ping_interval: float = 20,
23
ping_timeout: float = 20,
24
max_size: int = 2**20,
25
max_queue: int = 2**5,
26
read_limit: int = 2**16,
27
write_limit: int = 2**16,
28
extensions: List[ClientExtensionFactory] = None,
29
**kwargs
30
) -> ClientConnection:
31
"""
32
Connect to a WebSocket server.
33
34
Parameters:
35
- uri: WebSocket URI (ws:// or wss://)
36
- additional_headers: Extra HTTP headers for handshake
37
- user_agent_header: Custom User-Agent header
38
- compression: Compression mode ("deflate" or None)
39
- logger: Logger instance for connection logging
40
- subprotocols: List of supported subprotocols
41
- extra_headers: Additional headers (deprecated, use additional_headers)
42
- open_timeout: Timeout for connection establishment (seconds)
43
- close_timeout: Timeout for connection closure (seconds)
44
- ping_interval: Interval between ping frames (seconds)
45
- ping_timeout: Timeout for ping/pong exchange (seconds)
46
- max_size: Maximum message size (bytes)
47
- max_queue: Maximum number of queued messages
48
- read_limit: Buffer size for reading (bytes)
49
- write_limit: Buffer size for writing (bytes)
50
- extensions: List of WebSocket extensions
51
52
Returns:
53
ClientConnection: Async context manager and iterator for WebSocket communication
54
"""
55
56
async def unix_connect(
57
path: str,
58
*,
59
additional_headers: HeadersLike = None,
60
user_agent_header: str = None,
61
compression: str = "deflate",
62
logger: LoggerLike = None,
63
subprotocols: List[Subprotocol] = None,
64
extra_headers: HeadersLike = None,
65
open_timeout: float = 10,
66
close_timeout: float = 10,
67
ping_interval: float = 20,
68
ping_timeout: float = 20,
69
max_size: int = 2**20,
70
max_queue: int = 2**5,
71
read_limit: int = 2**16,
72
write_limit: int = 2**16,
73
extensions: List[ClientExtensionFactory] = None,
74
**kwargs
75
) -> ClientConnection:
76
"""
77
Connect to a WebSocket server over Unix domain socket.
78
79
Parameters:
80
- path: Unix domain socket path
81
- Other parameters same as connect()
82
83
Returns:
84
ClientConnection: WebSocket connection over Unix socket
85
"""
86
```
87
88
### Client Connection Management
89
90
The ClientConnection class provides the main interface for WebSocket client operations with support for async context management and message iteration.
91
92
```python { .api }
93
class ClientConnection:
94
"""WebSocket client connection with asyncio support."""
95
96
@property
97
def closed(self) -> bool:
98
"""Check if connection is closed."""
99
100
@property
101
def local_address(self) -> Tuple[str, int]:
102
"""Get local socket address."""
103
104
@property
105
def remote_address(self) -> Tuple[str, int]:
106
"""Get remote socket address."""
107
108
@property
109
def subprotocol(self) -> Subprotocol | None:
110
"""Get negotiated subprotocol."""
111
112
async def send(self, message: Data) -> None:
113
"""
114
Send a message to the WebSocket server.
115
116
Parameters:
117
- message: Text (str) or binary (bytes) message to send
118
119
Raises:
120
- ConnectionClosed: If connection is closed
121
"""
122
123
async def recv(self) -> Data:
124
"""
125
Receive a message from the WebSocket server.
126
127
Returns:
128
str | bytes: Received message (text or binary)
129
130
Raises:
131
- ConnectionClosed: If connection is closed
132
"""
133
134
async def ping(self, data: bytes = b"") -> Awaitable[float]:
135
"""
136
Send a ping frame and wait for pong response.
137
138
Parameters:
139
- data: Optional payload for ping frame
140
141
Returns:
142
Awaitable[float]: Coroutine that resolves to round-trip time
143
144
Raises:
145
- ConnectionClosed: If connection is closed
146
"""
147
148
async def pong(self, data: bytes = b"") -> None:
149
"""
150
Send a pong frame.
151
152
Parameters:
153
- data: Payload for pong frame
154
155
Raises:
156
- ConnectionClosed: If connection is closed
157
"""
158
159
async def close(self, code: int = 1000, reason: str = "") -> None:
160
"""
161
Close the WebSocket connection.
162
163
Parameters:
164
- code: Close code (default 1000 for normal closure)
165
- reason: Human-readable close reason
166
167
Raises:
168
- ProtocolError: If code is invalid
169
"""
170
171
async def wait_closed(self) -> None:
172
"""Wait until the connection is closed."""
173
174
# Context manager support
175
async def __aenter__(self) -> ClientConnection:
176
"""Enter async context manager."""
177
return self
178
179
async def __aexit__(self, exc_type, exc_value, traceback) -> None:
180
"""Exit async context manager and close connection."""
181
182
# Async iterator support
183
def __aiter__(self) -> AsyncIterator[Data]:
184
"""Return async iterator for receiving messages."""
185
return self
186
187
async def __anext__(self) -> Data:
188
"""Get next message from async iterator."""
189
```
190
191
### Error Classification
192
193
Utility function for classifying connection errors and determining appropriate handling strategies.
194
195
```python { .api }
196
def process_exception(exception: Exception) -> Exception:
197
"""
198
Classify exceptions for connection error handling.
199
200
Parameters:
201
- exception: Exception that occurred during connection
202
203
Returns:
204
Exception: Classified exception (may be the same or different type)
205
"""
206
```
207
208
## Usage Examples
209
210
### Basic Client Connection
211
212
```python
213
import asyncio
214
import websockets
215
216
async def basic_client():
217
# Simple connection with default settings
218
async with websockets.connect("ws://localhost:8765") as websocket:
219
await websocket.send("Hello, Server!")
220
response = await websocket.recv()
221
print(f"Server response: {response}")
222
223
asyncio.run(basic_client())
224
```
225
226
### Client with Custom Configuration
227
228
```python
229
import asyncio
230
import websockets
231
import logging
232
233
async def configured_client():
234
# Client with custom headers, compression, and logging
235
headers = {"Authorization": "Bearer token123"}
236
logger = logging.getLogger("websocket_client")
237
238
async with websockets.connect(
239
"wss://api.example.com/ws",
240
additional_headers=headers,
241
compression="deflate",
242
logger=logger,
243
ping_interval=30,
244
ping_timeout=10,
245
max_size=1024*1024 # 1MB max message size
246
) as websocket:
247
248
# Send JSON data
249
import json
250
data = {"type": "subscribe", "channel": "updates"}
251
await websocket.send(json.dumps(data))
252
253
# Listen for messages
254
async for message in websocket:
255
data = json.loads(message)
256
print(f"Received: {data}")
257
258
# Break on specific message
259
if data.get("type") == "close":
260
break
261
262
asyncio.run(configured_client())
263
```
264
265
### Connection with Error Handling
266
267
```python
268
import asyncio
269
import websockets
270
from websockets import ConnectionClosedError, InvalidURI
271
272
async def robust_client():
273
try:
274
async with websockets.connect(
275
"ws://localhost:8765",
276
open_timeout=5,
277
close_timeout=5
278
) as websocket:
279
280
# Send ping to test connectivity
281
pong_waiter = await websocket.ping()
282
latency = await pong_waiter
283
print(f"Connection latency: {latency:.3f}s")
284
285
# Send messages with error handling
286
for i in range(10):
287
try:
288
await websocket.send(f"Message {i}")
289
response = await websocket.recv()
290
print(f"Echo {i}: {response}")
291
except ConnectionClosedError:
292
print("Connection closed by server")
293
break
294
295
except InvalidURI as e:
296
print(f"Invalid WebSocket URI: {e}")
297
except ConnectionClosedError as e:
298
print(f"Connection failed: {e}")
299
except Exception as e:
300
print(f"Unexpected error: {e}")
301
302
asyncio.run(robust_client())
303
```
304
305
### Unix Domain Socket Client
306
307
```python
308
import asyncio
309
import websockets
310
311
async def unix_client():
312
# Connect via Unix domain socket
313
async with websockets.unix_connect("/tmp/websocket.sock") as websocket:
314
await websocket.send("Hello via Unix socket!")
315
response = await websocket.recv()
316
print(f"Response: {response}")
317
318
asyncio.run(unix_client())
319
```