WebSocket client for Python with low level API options
npx @tessl/cli install tessl/pypi-websocket-client@1.8.00
# WebSocket Client
1
2
A comprehensive WebSocket client implementation for Python that enables developers to establish and manage WebSocket connections with low-level API access. It implements the hybi-13 version of the WebSocket protocol and offers both high-level WebSocketApp class for simple use cases and low-level WebSocket class for advanced control over connection handling.
3
4
## Package Information
5
6
- **Package Name**: websocket-client
7
- **Language**: Python
8
- **Installation**: `pip install websocket-client`
9
10
## Core Imports
11
12
```python
13
import websocket
14
```
15
16
Common patterns for different use cases:
17
18
```python
19
# High-level event-driven interface
20
from websocket import WebSocketApp, setReconnect
21
22
# Low-level connection control
23
from websocket import WebSocket, create_connection
24
25
# Frame protocol and status codes
26
from websocket import ABNF, STATUS_NORMAL, STATUS_GOING_AWAY, STATUS_PROTOCOL_ERROR
27
28
# Exception handling
29
from websocket import WebSocketException, WebSocketConnectionClosedException
30
31
# Debugging and logging
32
from websocket import enableTrace
33
34
# Socket configuration
35
from websocket import setdefaulttimeout, getdefaulttimeout
36
```
37
38
## Basic Usage
39
40
### Simple Connection (Low-level)
41
42
```python
43
from websocket import create_connection
44
45
# Connect and exchange messages
46
ws = create_connection("ws://echo.websocket.events/")
47
print(ws.recv()) # Server greeting
48
ws.send("Hello, World")
49
result = ws.recv()
50
print(result) # "Hello, World"
51
ws.close()
52
```
53
54
### Event-Driven Application (High-level)
55
56
```python
57
import websocket
58
import rel
59
60
def on_message(ws, message):
61
print(f"Received: {message}")
62
63
def on_error(ws, error):
64
print(f"Error: {error}")
65
66
def on_close(ws, close_status_code, close_msg):
67
print("Connection closed")
68
69
def on_open(ws):
70
print("Connection opened")
71
72
# Create WebSocket application with callbacks
73
ws = websocket.WebSocketApp("wss://api.gemini.com/v1/marketdata/BTCUSD",
74
on_open=on_open,
75
on_message=on_message,
76
on_error=on_error,
77
on_close=on_close)
78
79
# Run with automatic reconnection
80
ws.run_forever(dispatcher=rel, reconnect=5)
81
rel.signal(2, rel.abort)
82
rel.dispatch()
83
```
84
85
## Architecture
86
87
The websocket-client library provides a layered architecture for WebSocket communication:
88
89
- **WebSocketApp**: High-level event-driven interface with automatic reconnection, ping/pong handling, and lifecycle callbacks
90
- **WebSocket**: Low-level connection class offering direct protocol control and frame-by-frame communication
91
- **ABNF**: Frame protocol implementation handling WebSocket message framing, masking, and validation
92
- **Connection Functions**: Utility functions for establishing connections with full configuration support
93
94
This design enables both simple use cases through WebSocketApp and advanced control through the low-level WebSocket class, supporting secure connections (wss://), proxy configurations, custom headers, and comprehensive error handling.
95
96
## Capabilities
97
98
### High-Level WebSocket Application
99
100
Event-driven WebSocket interface with automatic connection management, reconnection capabilities, and lifecycle callbacks. Ideal for applications requiring persistent connections with minimal configuration.
101
102
```python { .api }
103
class WebSocketApp:
104
def __init__(
105
self,
106
url: str,
107
header: Union[list, dict, Callable, None] = None,
108
on_open: Optional[Callable[[WebSocket], None]] = None,
109
on_reconnect: Optional[Callable[[WebSocket], None]] = None,
110
on_message: Optional[Callable[[WebSocket, Any], None]] = None,
111
on_error: Optional[Callable[[WebSocket, Any], None]] = None,
112
on_close: Optional[Callable[[WebSocket, Any, Any], None]] = None,
113
on_ping: Optional[Callable] = None,
114
on_pong: Optional[Callable] = None,
115
on_cont_message: Optional[Callable] = None,
116
keep_running: bool = True,
117
get_mask_key: Optional[Callable] = None,
118
cookie: Optional[str] = None,
119
subprotocols: Optional[list] = None,
120
on_data: Optional[Callable] = None,
121
socket: Optional[socket.socket] = None,
122
) -> None: ...
123
124
def run_forever(
125
self,
126
sockopt: tuple = None,
127
sslopt: dict = None,
128
ping_interval: Union[float, int] = 0,
129
ping_timeout: Union[float, int, None] = None,
130
ping_payload: str = "",
131
http_proxy_host: str = None,
132
http_proxy_port: Union[int, str] = None,
133
http_no_proxy: list = None,
134
http_proxy_auth: tuple = None,
135
http_proxy_timeout: Optional[float] = None,
136
skip_utf8_validation: bool = False,
137
host: str = None,
138
origin: str = None,
139
dispatcher=None,
140
suppress_origin: bool = False,
141
proxy_type: str = None,
142
reconnect: int = None,
143
) -> bool: ...
144
145
def send(self, data: Union[bytes, str], opcode: int = ABNF.OPCODE_TEXT) -> None: ...
146
def send_text(self, text_data: str) -> None: ...
147
def send_bytes(self, data: Union[bytes, bytearray]) -> None: ...
148
def close(self, **kwargs) -> None: ...
149
150
def setReconnect(reconnectInterval: int) -> None: ...
151
```
152
153
[High-Level WebSocket Application](./websocket-app.md)
154
155
### Low-Level WebSocket Interface
156
157
Direct WebSocket protocol control with frame-by-frame communication, custom connection options, and advanced features like manual ping/pong handling and continuation frames.
158
159
```python { .api }
160
class WebSocket:
161
def __init__(
162
self,
163
get_mask_key=None,
164
sockopt=None,
165
sslopt=None,
166
fire_cont_frame: bool = False,
167
enable_multithread: bool = True,
168
skip_utf8_validation: bool = False,
169
**_,
170
): ...
171
172
def connect(self, url, **options): ...
173
def send(self, payload: Union[bytes, str], opcode: int = ABNF.OPCODE_TEXT) -> int: ...
174
def send_text(self, text_data: str) -> int: ...
175
def send_bytes(self, data: Union[bytes, bytearray]) -> int: ...
176
def send_frame(self, frame) -> int: ...
177
def recv(self) -> Union[str, bytes]: ...
178
def recv_data(self, control_frame: bool = False) -> tuple: ...
179
def recv_data_frame(self, control_frame: bool = False) -> tuple: ...
180
def ping(self, payload: Union[str, bytes] = ""): ...
181
def pong(self, payload: Union[str, bytes] = ""): ...
182
def close(self, status: int = STATUS_NORMAL, reason: bytes = b"", timeout: int = 3): ...
183
184
def create_connection(url: str, timeout=None, class_=WebSocket, **options) -> WebSocket: ...
185
```
186
187
[Low-Level WebSocket Interface](./websocket-core.md)
188
189
### Frame Protocol and Status Codes
190
191
WebSocket frame handling, message types, and protocol status codes for low-level protocol control and custom frame processing.
192
193
```python { .api }
194
class ABNF:
195
OPCODE_CONT = 0x0
196
OPCODE_TEXT = 0x1
197
OPCODE_BINARY = 0x2
198
OPCODE_CLOSE = 0x8
199
OPCODE_PING = 0x9
200
OPCODE_PONG = 0xa
201
202
def __init__(
203
self,
204
fin: int = 0,
205
rsv1: int = 0,
206
rsv2: int = 0,
207
rsv3: int = 0,
208
opcode: int = OPCODE_TEXT,
209
mask_value: int = 1,
210
data: Union[str, bytes, None] = "",
211
) -> None: ...
212
213
def validate(self, skip_utf8_validation: bool = False) -> None: ...
214
@staticmethod
215
def create_frame(data: Union[bytes, str], opcode: int, fin: int = 1) -> "ABNF": ...
216
def format(self) -> bytes: ...
217
@staticmethod
218
def mask(mask_key: Union[str, bytes], data: Union[str, bytes]) -> bytes: ...
219
220
# Status codes
221
STATUS_NORMAL = 1000
222
STATUS_GOING_AWAY = 1001
223
STATUS_PROTOCOL_ERROR = 1002
224
STATUS_UNSUPPORTED_DATA_TYPE = 1003
225
STATUS_INVALID_PAYLOAD = 1007
226
STATUS_POLICY_VIOLATION = 1008
227
STATUS_MESSAGE_TOO_BIG = 1009
228
STATUS_INVALID_EXTENSION = 1010
229
STATUS_UNEXPECTED_CONDITION = 1011
230
```
231
232
[Frame Protocol and Status Codes](./abnf-protocol.md)
233
234
### Exception Handling
235
236
Comprehensive exception hierarchy for WebSocket-specific error conditions, connection management, and protocol violations.
237
238
```python { .api }
239
class WebSocketException(Exception): ...
240
class WebSocketProtocolException(WebSocketException): ...
241
class WebSocketPayloadException(WebSocketException): ...
242
class WebSocketConnectionClosedException(WebSocketException): ...
243
class WebSocketTimeoutException(WebSocketException): ...
244
class WebSocketProxyException(WebSocketException): ...
245
class WebSocketBadStatusException(WebSocketException):
246
def __init__(
247
self,
248
message: str,
249
status_code: int,
250
status_message=None,
251
resp_headers=None,
252
resp_body=None,
253
): ...
254
class WebSocketAddressException(WebSocketException): ...
255
```
256
257
[Exception Handling](./exceptions.md)
258
259
### Debug and Logging
260
261
Debugging utilities and logging functions for tracing WebSocket communication, protocol analysis, and troubleshooting connection issues.
262
263
```python { .api }
264
def enableTrace(
265
traceable: bool,
266
handler: logging.StreamHandler = logging.StreamHandler(),
267
level: str = "DEBUG",
268
) -> None: ...
269
270
def dump(title: str, message: str) -> None: ...
271
def error(msg: str) -> None: ...
272
def warning(msg: str) -> None: ...
273
def debug(msg: str) -> None: ...
274
def info(msg: str) -> None: ...
275
def trace(msg: str) -> None: ...
276
def isEnabledForError() -> bool: ...
277
def isEnabledForDebug() -> bool: ...
278
def isEnabledForTrace() -> bool: ...
279
```
280
281
[Debug and Logging](./logging.md)
282
283
### Socket Configuration
284
285
Low-level socket configuration, timeout management, and network-level options for advanced connection control and performance tuning.
286
287
```python { .api }
288
DEFAULT_SOCKET_OPTION: list
289
290
class sock_opt:
291
def __init__(self, sockopt: list, sslopt: dict) -> None: ...
292
293
def setdefaulttimeout(timeout: Union[int, float, None]) -> None: ...
294
def getdefaulttimeout() -> Union[int, float, None]: ...
295
def recv(sock: socket.socket, bufsize: int) -> bytes: ...
296
def recv_line(sock: socket.socket) -> bytes: ...
297
def send(sock: socket.socket, data: Union[bytes, str]) -> int: ...
298
```
299
300
[Socket Configuration](./socket-config.md)
301
302
### Command-Line Tools
303
304
The websocket-client package includes the `wsdump` command-line utility for interactive WebSocket debugging and testing.
305
306
```bash
307
# Install websocket-client to get wsdump command
308
pip install websocket-client
309
310
# Basic usage - connect to WebSocket URL
311
wsdump ws://echo.websocket.events/
312
313
# With proxy support
314
wsdump --proxy http://127.0.0.1:8080 ws://example.com/ws
315
316
# Enable verbose output (show opcodes)
317
wsdump -v ws://echo.websocket.events/
318
319
# Enable full debug tracing
320
wsdump -vv ws://echo.websocket.events/
321
322
# Send initial text message
323
wsdump --text "Hello Server" ws://echo.websocket.events/
324
325
# Ignore SSL certificate errors
326
wsdump --nocert wss://self-signed.badssl.com/
327
328
# Set custom headers
329
wsdump --headers "Authorization: Bearer token,X-Custom: value" ws://api.example.com/ws
330
```