0
# WebSockets
1
2
A comprehensive Python library implementing the WebSocket Protocol (RFC 6455 & 7692) with both asynchronous (asyncio) and synchronous (threading) APIs. Provides production-ready WebSocket server and client functionality with extensive protocol support, compression, routing, authentication, and error handling.
3
4
## Package Information
5
6
- **Package Name**: websockets
7
- **Language**: Python
8
- **Version**: 15.0.1
9
- **Installation**: `pip install websockets`
10
- **Documentation**: https://websockets.readthedocs.io/
11
12
## Core Imports
13
14
```python
15
import websockets
16
```
17
18
Asyncio WebSocket operations:
19
20
```python
21
from websockets import connect, serve, broadcast
22
from websockets import ClientConnection, ServerConnection, Server
23
```
24
25
Synchronous WebSocket operations:
26
27
```python
28
from websockets.sync import connect, serve
29
from websockets.sync import ClientConnection, ServerConnection, Server
30
```
31
32
Exception handling:
33
34
```python
35
from websockets import (
36
ConnectionClosed, ConnectionClosedError, ConnectionClosedOK,
37
InvalidHandshake, ProtocolError, WebSocketException
38
)
39
```
40
41
## Basic Usage
42
43
### Asyncio Client
44
45
```python
46
import asyncio
47
import websockets
48
49
async def client_example():
50
async with websockets.connect("ws://localhost:8765") as websocket:
51
# Send a message
52
await websocket.send("Hello, Server!")
53
54
# Receive a message
55
message = await websocket.recv()
56
print(f"Received: {message}")
57
58
# Run the client
59
asyncio.run(client_example())
60
```
61
62
### Asyncio Server
63
64
```python
65
import asyncio
66
import websockets
67
68
async def handler(websocket):
69
async for message in websocket:
70
print(f"Received: {message}")
71
# Echo the message back
72
await websocket.send(f"Echo: {message}")
73
74
async def server_example():
75
async with websockets.serve(handler, "localhost", 8765):
76
print("WebSocket server started on ws://localhost:8765")
77
await asyncio.Future() # Run forever
78
79
# Run the server
80
asyncio.run(server_example())
81
```
82
83
### Synchronous Client
84
85
```python
86
from websockets.sync import connect
87
88
def sync_client_example():
89
with connect("ws://localhost:8765") as websocket:
90
# Send a message
91
websocket.send("Hello, Server!")
92
93
# Receive a message
94
message = websocket.recv()
95
print(f"Received: {message}")
96
97
sync_client_example()
98
```
99
100
## Architecture
101
102
The websockets library follows a layered architecture:
103
104
- **Sans-I/O Protocol Layer**: Core WebSocket protocol implementation (`Protocol`, `ClientProtocol`, `ServerProtocol`)
105
- **I/O Implementation Layer**: Asyncio and synchronous I/O implementations (`asyncio.*`, `sync.*`)
106
- **Connection Management**: High-level connection classes (`ClientConnection`, `ServerConnection`, `Server`)
107
- **Extension System**: Modular support for WebSocket extensions like per-message deflate compression
108
- **Routing System**: Integration with werkzeug for URL pattern matching and request routing
109
110
This design provides flexibility to use WebSocket functionality in different contexts while maintaining protocol correctness and enabling custom extensions.
111
112
## Capabilities
113
114
### Asyncio Client Operations
115
116
High-level asyncio-based WebSocket client functionality including connection management, message sending/receiving, and connection lifecycle handling with async context managers and iterators.
117
118
```python { .api }
119
async def connect(uri: str, **kwargs) -> ClientConnection: ...
120
async def unix_connect(path: str, **kwargs) -> ClientConnection: ...
121
122
class ClientConnection:
123
async def send(self, message: str | bytes) -> None: ...
124
async def recv(self) -> str | bytes: ...
125
async def close(self, code: int = 1000, reason: str = "") -> None: ...
126
async def __aenter__(self) -> ClientConnection: ...
127
async def __aexit__(self, *args) -> None: ...
128
def __aiter__(self) -> AsyncIterator[str | bytes]: ...
129
```
130
131
[Asyncio Client](./asyncio-client.md)
132
133
### Asyncio Server Operations
134
135
Complete asyncio-based WebSocket server functionality including server lifecycle management, connection handling, message broadcasting, and authentication support.
136
137
```python { .api }
138
async def serve(handler: Callable, host: str, port: int, **kwargs) -> Server: ...
139
async def unix_serve(handler: Callable, path: str, **kwargs) -> Server: ...
140
def broadcast(connections: Iterable[ServerConnection], message: str | bytes) -> None: ...
141
def basic_auth(username: str, password: str) -> Callable: ...
142
143
class ServerConnection:
144
async def send(self, message: str | bytes) -> None: ...
145
async def recv(self) -> str | bytes: ...
146
async def close(self, code: int = 1000, reason: str = "") -> None: ...
147
148
class Server:
149
async def __aenter__(self) -> Server: ...
150
async def __aexit__(self, *args) -> None: ...
151
def close(self) -> None: ...
152
```
153
154
[Asyncio Server](./asyncio-server.md)
155
156
### Synchronous Client Operations
157
158
Threading-based synchronous WebSocket client functionality providing blocking operations for environments where asyncio is not suitable or preferred.
159
160
```python { .api }
161
def connect(uri: str, **kwargs) -> ClientConnection: ...
162
def unix_connect(path: str, **kwargs) -> ClientConnection: ...
163
164
class ClientConnection:
165
def send(self, message: str | bytes) -> None: ...
166
def recv(self) -> str | bytes: ...
167
def close(self, code: int = 1000, reason: str = "") -> None: ...
168
def __enter__(self) -> ClientConnection: ...
169
def __exit__(self, *args) -> None: ...
170
def __iter__(self) -> Iterator[str | bytes]: ...
171
```
172
173
[Synchronous Client](./sync-client.md)
174
175
### Synchronous Server Operations
176
177
Complete threading-based synchronous WebSocket server functionality for traditional Python applications that don't use asyncio.
178
179
```python { .api }
180
def serve(handler: Callable, host: str, port: int, **kwargs) -> Server: ...
181
def unix_serve(handler: Callable, path: str, **kwargs) -> Server: ...
182
def basic_auth(username: str, password: str) -> Callable: ...
183
184
class ServerConnection:
185
def send(self, message: str | bytes) -> None: ...
186
def recv(self) -> str | bytes: ...
187
def close(self, code: int = 1000, reason: str = "") -> None: ...
188
189
class Server:
190
def __enter__(self) -> Server: ...
191
def __exit__(self, *args) -> None: ...
192
def close(self) -> None: ...
193
```
194
195
[Synchronous Server](./sync-server.md)
196
197
### Protocol Implementation
198
199
Sans-I/O WebSocket protocol implementation providing the core WebSocket functionality independent of I/O handling, enabling custom integrations and advanced use cases.
200
201
```python { .api }
202
class Protocol:
203
def __init__(self, side: Side, **kwargs): ...
204
def send(self, message: str | bytes) -> bytes: ...
205
def recv(self, data: bytes) -> List[str | bytes]: ...
206
def close(self, code: int = 1000, reason: str = "") -> bytes: ...
207
208
class ClientProtocol(Protocol): ...
209
class ServerProtocol(Protocol): ...
210
211
class Side(Enum):
212
CLIENT = "client"
213
SERVER = "server"
214
215
class State(Enum):
216
CONNECTING = "connecting"
217
OPEN = "open"
218
CLOSING = "closing"
219
CLOSED = "closed"
220
```
221
222
[Protocol Implementation](./protocol.md)
223
224
### Routing and URL Handling
225
226
WebSocket server routing with werkzeug integration for URL pattern matching, parameter extraction, and request routing to different handlers based on URL patterns.
227
228
```python { .api }
229
async def route(router: Router, host: str, port: int, **kwargs) -> Server: ...
230
async def unix_route(router: Router, path: str, **kwargs) -> Server: ...
231
232
class Router:
233
def __init__(self): ...
234
def route(self, path: str, **kwargs) -> Callable: ...
235
def add_route(self, handler: Callable, path: str, **kwargs) -> None: ...
236
```
237
238
[Routing](./routing.md)
239
240
### Exception Handling
241
242
Comprehensive exception hierarchy for precise error handling covering connection lifecycle, protocol violations, handshake failures, and validation errors.
243
244
```python { .api }
245
class WebSocketException(Exception): ...
246
class ConnectionClosed(WebSocketException): ...
247
class ConnectionClosedOK(ConnectionClosed): ...
248
class ConnectionClosedError(ConnectionClosed): ...
249
class InvalidHandshake(WebSocketException): ...
250
class ProtocolError(WebSocketException): ...
251
class SecurityError(InvalidHandshake): ...
252
class PayloadTooBig(ProtocolError): ...
253
```
254
255
[Exception Handling](./exceptions.md)
256
257
### Data Structures and Types
258
259
Core data structures for HTTP headers, WebSocket frames, close codes, and type definitions used throughout the WebSocket implementation.
260
261
```python { .api }
262
class Headers:
263
def __init__(self, *args, **kwargs): ...
264
def __getitem__(self, key: str) -> str: ...
265
def __setitem__(self, key: str, value: str) -> None: ...
266
def get(self, key: str, default: str = None) -> str: ...
267
268
class Frame:
269
def __init__(self, opcode: Opcode, data: bytes, fin: bool = True): ...
270
271
class Opcode(Enum):
272
CONT = 0
273
TEXT = 1
274
BINARY = 2
275
CLOSE = 8
276
PING = 9
277
PONG = 10
278
279
class CloseCode(Enum):
280
NORMAL_CLOSURE = 1000
281
GOING_AWAY = 1001
282
PROTOCOL_ERROR = 1002
283
```
284
285
[Data Structures](./data-structures.md)
286
287
### Extensions and Compression
288
289
WebSocket extension system with built-in per-message deflate compression support (RFC 7692) and extensible framework for custom extensions.
290
291
```python { .api }
292
def enable_client_permessage_deflate(**kwargs) -> List[ClientExtensionFactory]: ...
293
def enable_server_permessage_deflate(**kwargs) -> List[ServerExtensionFactory]: ...
294
295
class ClientPerMessageDeflateFactory:
296
def __init__(self, **kwargs): ...
297
298
class ServerPerMessageDeflateFactory:
299
def __init__(self, **kwargs): ...
300
301
class Extension:
302
def encode(self, frame: Frame) -> Frame: ...
303
def decode(self, frame: Frame) -> Frame: ...
304
```
305
306
[Extensions](./extensions.md)
307
308
## Common Type Definitions
309
310
```python { .api }
311
# Type aliases used throughout the API
312
Data = str | bytes # WebSocket message content
313
HeadersLike = Dict[str, str] | List[Tuple[str, str]] | Headers # Header input formats
314
Origin = str # Origin header value
315
Subprotocol = str # WebSocket subprotocol name
316
ExtensionName = str # WebSocket extension name
317
ExtensionParameter = Tuple[str, str | None] # Extension parameter
318
LoggerLike = logging.Logger | logging.LoggerAdapter # Logger types
319
StatusLike = int | HTTPStatus # HTTP status types
320
```