0
# Low-Level WebSocket Interface
1
2
Direct WebSocket protocol control with frame-by-frame communication, custom connection options, and advanced features like manual ping/pong handling and continuation frames. The WebSocket class provides fine-grained control over the WebSocket protocol for advanced use cases.
3
4
## Capabilities
5
6
### WebSocket Class
7
8
Low-level WebSocket interface offering direct protocol control and comprehensive configuration options.
9
10
```python { .api }
11
class WebSocket:
12
def __init__(
13
self,
14
get_mask_key=None,
15
sockopt=None,
16
sslopt=None,
17
fire_cont_frame: bool = False,
18
enable_multithread: bool = True,
19
skip_utf8_validation: bool = False,
20
**_,
21
):
22
"""
23
Initialize WebSocket object.
24
25
Parameters:
26
- get_mask_key: Function to generate mask keys for frame masking
27
- sockopt: Socket options list for socket.setsockopt calls
28
- sslopt: SSL options dictionary for SSL socket configuration
29
- fire_cont_frame: Whether to fire events for continuation frames
30
- enable_multithread: Enable thread-safe operations with locks
31
- skip_utf8_validation: Skip UTF-8 validation for performance
32
"""
33
```
34
35
### Connection Management
36
37
Establish and manage WebSocket connections with comprehensive configuration options.
38
39
```python { .api }
40
def connect(self, url, **options):
41
"""
42
Connect to WebSocket URL with extensive configuration options.
43
44
Parameters:
45
- url: WebSocket URL (ws:// or wss://)
46
- header: Custom headers (list or dict)
47
- cookie: Cookie string for authentication
48
- origin: Custom origin URL
49
- connection: Custom connection header (default: "Upgrade")
50
- suppress_origin: Don't send Origin header
51
- host: Custom host header
52
- timeout: Socket timeout in seconds
53
- http_proxy_host: HTTP proxy hostname
54
- http_proxy_port: HTTP proxy port
55
- http_no_proxy: Hosts that bypass proxy
56
- http_proxy_auth: Proxy auth tuple (username, password)
57
- http_proxy_timeout: Proxy connection timeout
58
- redirect_limit: Maximum redirects to follow
59
- subprotocols: List of supported subprotocols
60
- socket: Pre-initialized socket object
61
"""
62
63
def close(self, status: int = STATUS_NORMAL, reason: bytes = b"", timeout: int = 3):
64
"""
65
Close WebSocket connection gracefully.
66
67
Parameters:
68
- status: Close status code (see STATUS_* constants)
69
- reason: UTF-8 encoded close reason
70
- timeout: Timeout to wait for close frame response
71
72
Raises:
73
ValueError: If status code is invalid range
74
"""
75
76
def abort(self):
77
"""
78
Immediately abort connection without close handshake.
79
Wakes up threads waiting in recv operations.
80
"""
81
82
def shutdown(self):
83
"""
84
Close socket immediately without WebSocket close handshake.
85
"""
86
```
87
88
### Message Sending
89
90
Send various types of messages and frames with precise control over WebSocket opcodes.
91
92
```python { .api }
93
def send(self, payload: Union[bytes, str], opcode: int = ABNF.OPCODE_TEXT) -> int:
94
"""
95
Send data with specified opcode.
96
97
Parameters:
98
- payload: Data to send (string for text, bytes for binary)
99
- opcode: WebSocket opcode (OPCODE_TEXT, OPCODE_BINARY, etc.)
100
101
Returns:
102
int: Number of bytes sent
103
"""
104
105
def send_text(self, text_data: str) -> int:
106
"""
107
Send UTF-8 text message.
108
109
Parameters:
110
- text_data: Text string to send
111
112
Returns:
113
int: Number of bytes sent
114
"""
115
116
def send_bytes(self, data: Union[bytes, bytearray]) -> int:
117
"""
118
Send binary message.
119
120
Parameters:
121
- data: Binary data to send
122
123
Returns:
124
int: Number of bytes sent
125
"""
126
127
def send_binary(self, payload: bytes) -> int:
128
"""
129
Send binary message (alias for send with OPCODE_BINARY).
130
131
Parameters:
132
- payload: Binary data to send
133
134
Returns:
135
int: Number of bytes sent
136
"""
137
138
def send_frame(self, frame) -> int:
139
"""
140
Send raw ABNF frame.
141
142
Parameters:
143
- frame: ABNF frame object
144
145
Returns:
146
int: Number of bytes sent
147
"""
148
```
149
150
### Message Receiving
151
152
Receive messages and frames with different levels of detail and control.
153
154
```python { .api }
155
def recv(self) -> Union[str, bytes]:
156
"""
157
Receive message data.
158
159
Returns:
160
Union[str, bytes]: Text messages as str, binary messages as bytes
161
"""
162
163
def recv_data(self, control_frame: bool = False) -> tuple:
164
"""
165
Receive data with opcode information.
166
167
Parameters:
168
- control_frame: Whether to return control frame data
169
170
Returns:
171
tuple: (opcode, data) - opcode and message data
172
"""
173
174
def recv_data_frame(self, control_frame: bool = False) -> tuple:
175
"""
176
Receive complete frame with opcode.
177
178
Parameters:
179
- control_frame: Whether to return control frame data
180
181
Returns:
182
tuple: (opcode, frame) - opcode and ABNF frame object
183
"""
184
185
def recv_frame(self):
186
"""
187
Receive raw ABNF frame from server.
188
189
Returns:
190
ABNF: Raw frame object with all protocol details
191
"""
192
```
193
194
### Control Frame Handling
195
196
Send and manage WebSocket control frames for connection health monitoring.
197
198
```python { .api }
199
def ping(self, payload: Union[str, bytes] = ""):
200
"""
201
Send ping frame to server.
202
203
Parameters:
204
- payload: Optional payload data for ping
205
206
Note: Payload is automatically UTF-8 encoded if string
207
"""
208
209
def pong(self, payload: Union[str, bytes] = ""):
210
"""
211
Send pong frame to server.
212
213
Parameters:
214
- payload: Optional payload data for pong
215
216
Note: Payload is automatically UTF-8 encoded if string
217
"""
218
219
def send_close(self, status: int = STATUS_NORMAL, reason: bytes = b""):
220
"""
221
Send close frame without waiting for response.
222
223
Parameters:
224
- status: Close status code
225
- reason: UTF-8 encoded close reason
226
227
Raises:
228
ValueError: If status code is invalid range
229
"""
230
```
231
232
### Configuration and Properties
233
234
Access connection properties and configure WebSocket behavior.
235
236
```python { .api }
237
def set_mask_key(self, func):
238
"""
239
Set custom mask key generator function.
240
241
Parameters:
242
- func: Callable that takes length integer and returns bytes
243
"""
244
245
def gettimeout(self) -> Union[float, int, None]:
246
"""
247
Get current socket timeout.
248
249
Returns:
250
Union[float, int, None]: Timeout in seconds or None for blocking
251
"""
252
253
def settimeout(self, timeout: Union[float, int, None]):
254
"""
255
Set socket timeout.
256
257
Parameters:
258
- timeout: Timeout in seconds or None for blocking
259
"""
260
261
def getsubprotocol(self):
262
"""
263
Get negotiated subprotocol.
264
265
Returns:
266
str: Negotiated subprotocol name or None
267
"""
268
269
def getstatus(self):
270
"""
271
Get handshake HTTP status code.
272
273
Returns:
274
int: HTTP status code from handshake response
275
"""
276
277
def getheaders(self):
278
"""
279
Get handshake response headers.
280
281
Returns:
282
dict: HTTP headers from handshake response
283
"""
284
285
def is_ssl(self):
286
"""
287
Check if connection uses SSL/TLS.
288
289
Returns:
290
bool: True if SSL connection, False otherwise
291
"""
292
293
def fileno(self):
294
"""
295
Get socket file descriptor.
296
297
Returns:
298
int: Socket file descriptor for select/poll operations
299
"""
300
301
# Properties for convenient access
302
timeout = property(gettimeout, settimeout)
303
subprotocol = property(getsubprotocol)
304
status = property(getstatus)
305
headers = property(getheaders)
306
```
307
308
### Connection Factory Function
309
310
Utility function to create and connect WebSocket instances with extensive configuration.
311
312
```python { .api }
313
def create_connection(url: str, timeout=None, class_=WebSocket, **options) -> WebSocket:
314
"""
315
Create and connect WebSocket instance.
316
317
Parameters:
318
- url: WebSocket URL
319
- timeout: Connection timeout in seconds
320
- class_: WebSocket class to instantiate (for customization)
321
- **options: All WebSocket.connect() options plus:
322
- sockopt: Socket options list
323
- sslopt: SSL options dict
324
- fire_cont_frame: Enable continuation frame events
325
- enable_multithread: Enable thread-safe operations
326
- skip_utf8_validation: Skip UTF-8 validation
327
328
Returns:
329
WebSocket: Connected WebSocket instance
330
331
Raises:
332
Various WebSocket exceptions on connection failure
333
"""
334
```
335
336
## Usage Examples
337
338
### Simple Request-Response Pattern
339
340
```python
341
from websocket import create_connection
342
343
# Connect and exchange single message
344
ws = create_connection("ws://echo.websocket.events/")
345
print("Connected:", ws.getstatus())
346
print("Server says:", ws.recv())
347
348
ws.send("Hello, World!")
349
response = ws.recv()
350
print("Echo:", response)
351
ws.close()
352
```
353
354
### Binary Data Transfer
355
356
```python
357
from websocket import WebSocket
358
import struct
359
360
ws = WebSocket()
361
ws.connect("ws://example.com/binary-api")
362
363
# Send binary data
364
data = struct.pack("!I", 12345)
365
ws.send_bytes(data)
366
367
# Receive binary response
368
response = ws.recv()
369
if isinstance(response, bytes):
370
value = struct.unpack("!I", response)[0]
371
print(f"Received number: {value}")
372
373
ws.close()
374
```
375
376
### Custom Headers and Authentication
377
378
```python
379
from websocket import create_connection
380
381
# Connect with custom headers
382
headers = [
383
"Authorization: Bearer your-jwt-token",
384
"X-Client-Version: 1.0",
385
"User-Agent: MyApp/1.0"
386
]
387
388
ws = create_connection(
389
"wss://api.example.com/websocket",
390
header=headers,
391
origin="https://myapp.com"
392
)
393
394
print("Connected with headers")
395
print("Response headers:", ws.headers)
396
ws.close()
397
```
398
399
### SSL/TLS Configuration
400
401
```python
402
from websocket import create_connection
403
import ssl
404
405
# Custom SSL configuration
406
sslopt = {
407
"cert_reqs": ssl.CERT_REQUIRED,
408
"ca_certs": "/etc/ssl/certs/ca-certificates.crt",
409
"certfile": "/path/to/client.crt",
410
"keyfile": "/path/to/client.key",
411
"ssl_version": ssl.PROTOCOL_TLS,
412
"ciphers": "HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!SRP:!CAMELLIA"
413
}
414
415
ws = create_connection("wss://secure.example.com/websocket", sslopt=sslopt)
416
print("Secure connection established")
417
print("Using SSL:", ws.is_ssl())
418
ws.close()
419
```
420
421
### Proxy Configuration
422
423
```python
424
from websocket import create_connection
425
426
# HTTP proxy
427
ws = create_connection(
428
"ws://echo.websocket.events/",
429
http_proxy_host="proxy.company.com",
430
http_proxy_port=8080,
431
http_proxy_auth=("username", "password")
432
)
433
434
# SOCKS proxy
435
ws = create_connection(
436
"ws://echo.websocket.events/",
437
http_proxy_host="socks-proxy.company.com",
438
http_proxy_port=1080,
439
proxy_type="socks5"
440
)
441
```
442
443
### Frame-Level Communication
444
445
```python
446
from websocket import WebSocket, ABNF
447
448
ws = WebSocket()
449
ws.connect("ws://echo.websocket.events/")
450
451
# Send custom frame
452
frame = ABNF.create_frame("Hello", ABNF.OPCODE_TEXT)
453
ws.send_frame(frame)
454
455
# Receive and examine frame
456
opcode, received_frame = ws.recv_data_frame()
457
print(f"Received opcode: {opcode}")
458
print(f"Frame data: {received_frame.data}")
459
print(f"Frame info: fin={received_frame.fin}, opcode={received_frame.opcode}")
460
461
ws.close()
462
```
463
464
### Ping/Pong Handling
465
466
```python
467
from websocket import WebSocket, ABNF
468
import time
469
470
ws = WebSocket()
471
ws.connect("ws://echo.websocket.events/")
472
473
# Send ping
474
ws.ping("ping-payload")
475
476
# Manually handle frames
477
while True:
478
opcode, frame = ws.recv_data_frame(control_frame=True)
479
480
if opcode == ABNF.OPCODE_PONG:
481
print(f"Received pong: {frame.data}")
482
break
483
elif opcode == ABNF.OPCODE_PING:
484
print("Received ping, sending pong")
485
ws.pong(frame.data)
486
elif opcode == ABNF.OPCODE_CLOSE:
487
print("Server closed connection")
488
break
489
490
ws.close()
491
```
492
493
### Iterator Interface
494
495
```python
496
from websocket import create_connection
497
498
ws = create_connection("ws://echo.websocket.events/")
499
500
# Send some test messages
501
for i in range(3):
502
ws.send(f"Message {i}")
503
504
# Use iterator interface to receive
505
try:
506
for message in ws:
507
print(f"Received: {message}")
508
if "Message 2" in message:
509
break
510
except KeyboardInterrupt:
511
pass
512
513
ws.close()
514
```