0
# High-Level WebSocket Application
1
2
Event-driven WebSocket interface providing automatic connection management, reconnection capabilities, and lifecycle callbacks. The WebSocketApp class offers a JavaScript WebSocket-like API ideal for applications requiring persistent connections with minimal configuration.
3
4
## Capabilities
5
6
### WebSocketApp Class
7
8
High-level WebSocket client with automatic connection management, event-driven callbacks, and built-in reconnection support.
9
10
```python { .api }
11
class WebSocketApp:
12
def __init__(
13
self,
14
url: str,
15
header: Union[list, dict, Callable, None] = None,
16
on_open: Optional[Callable[[WebSocket], None]] = None,
17
on_reconnect: Optional[Callable[[WebSocket], None]] = None,
18
on_message: Optional[Callable[[WebSocket, Any], None]] = None,
19
on_error: Optional[Callable[[WebSocket, Any], None]] = None,
20
on_close: Optional[Callable[[WebSocket, Any, Any], None]] = None,
21
on_ping: Optional[Callable] = None,
22
on_pong: Optional[Callable] = None,
23
on_cont_message: Optional[Callable] = None,
24
keep_running: bool = True,
25
get_mask_key: Optional[Callable] = None,
26
cookie: Optional[str] = None,
27
subprotocols: Optional[list] = None,
28
on_data: Optional[Callable] = None,
29
socket: Optional[socket.socket] = None,
30
) -> None:
31
"""
32
WebSocketApp initialization.
33
34
Parameters:
35
- url: WebSocket URL (ws:// or wss://)
36
- header: Custom headers as list, dict, or callable returning headers
37
- on_open: Callback called when connection opens (ws)
38
- on_reconnect: Callback called when reconnecting (ws)
39
- on_message: Callback called when message received (ws, message)
40
- on_error: Callback called on error (ws, error)
41
- on_close: Callback called when connection closes (ws, status_code, reason)
42
- on_ping: Callback called when ping received
43
- on_pong: Callback called when pong received
44
- on_cont_message: Callback called for continuation frames (ws, data, is_final)
45
- keep_running: Obsolete parameter, ignored
46
- get_mask_key: Function to generate mask keys
47
- cookie: Cookie string for authentication
48
- subprotocols: List of supported subprotocols
49
- on_data: Callback called before on_message (ws, data, opcode, is_final)
50
- socket: Pre-initialized socket object
51
"""
52
```
53
54
### Event Loop and Connection Management
55
56
Run the WebSocket event loop with comprehensive configuration options for connection handling, proxies, and automatic reconnection.
57
58
```python { .api }
59
def run_forever(
60
self,
61
sockopt: tuple = None,
62
sslopt: dict = None,
63
ping_interval: Union[float, int] = 0,
64
ping_timeout: Union[float, int, None] = None,
65
ping_payload: str = "",
66
http_proxy_host: str = None,
67
http_proxy_port: Union[int, str] = None,
68
http_no_proxy: list = None,
69
http_proxy_auth: tuple = None,
70
http_proxy_timeout: Optional[float] = None,
71
skip_utf8_validation: bool = False,
72
host: str = None,
73
origin: str = None,
74
dispatcher=None,
75
suppress_origin: bool = False,
76
proxy_type: str = None,
77
reconnect: int = None,
78
) -> bool:
79
"""
80
Run WebSocket event loop until connection closes.
81
82
Parameters:
83
- sockopt: Socket options tuple for socket.setsockopt
84
- sslopt: SSL options dictionary
85
- ping_interval: Auto-ping interval in seconds (0 = disabled)
86
- ping_timeout: Pong timeout in seconds
87
- ping_payload: Payload for ping messages
88
- http_proxy_host: HTTP proxy hostname
89
- http_proxy_port: HTTP proxy port
90
- http_no_proxy: Hosts that bypass proxy
91
- http_proxy_auth: Proxy authentication (username, password)
92
- http_proxy_timeout: Proxy connection timeout
93
- skip_utf8_validation: Skip UTF-8 validation for performance
94
- host: Custom Host header
95
- origin: Custom Origin header
96
- dispatcher: External event dispatcher (e.g., rel)
97
- suppress_origin: Don't send Origin header
98
- proxy_type: Proxy type (http, socks4, socks4a, socks5, socks5h)
99
- reconnect: Reconnection delay in seconds
100
101
Returns:
102
bool: True if error occurred, False if clean shutdown
103
"""
104
```
105
106
### Message Sending
107
108
Send different types of messages through the WebSocket connection with automatic opcode handling.
109
110
```python { .api }
111
def send(self, data: Union[bytes, str], opcode: int = ABNF.OPCODE_TEXT) -> None:
112
"""
113
Send message with specified opcode.
114
115
Parameters:
116
- data: Message data (string for text, bytes for binary)
117
- opcode: WebSocket opcode (OPCODE_TEXT, OPCODE_BINARY, etc.)
118
119
Raises:
120
WebSocketConnectionClosedException: If connection is closed
121
"""
122
123
def send_text(self, text_data: str) -> None:
124
"""
125
Send UTF-8 text message.
126
127
Parameters:
128
- text_data: Text string to send
129
130
Raises:
131
WebSocketConnectionClosedException: If connection is closed
132
"""
133
134
def send_bytes(self, data: Union[bytes, bytearray]) -> None:
135
"""
136
Send binary message.
137
138
Parameters:
139
- data: Binary data to send
140
141
Raises:
142
WebSocketConnectionClosedException: If connection is closed
143
"""
144
```
145
146
### Connection Control
147
148
Close and manage the WebSocket connection lifecycle.
149
150
```python { .api }
151
def close(self, **kwargs) -> None:
152
"""
153
Close WebSocket connection.
154
155
Parameters:
156
- **kwargs: Additional arguments passed to underlying close method
157
"""
158
```
159
160
### Global Reconnection Configuration
161
162
Configure global reconnection behavior for all WebSocketApp instances.
163
164
```python { .api }
165
def setReconnect(reconnectInterval: int) -> None:
166
"""
167
Set global reconnection interval.
168
169
Parameters:
170
- reconnectInterval: Delay in seconds between reconnection attempts
171
"""
172
```
173
174
## Usage Examples
175
176
### Basic Event-Driven Connection
177
178
```python
179
import websocket
180
181
def on_message(ws, message):
182
print(f"Received: {message}")
183
ws.send("Echo: " + message)
184
185
def on_error(ws, error):
186
print(f"Error: {error}")
187
188
def on_close(ws, close_status_code, close_msg):
189
print("Connection closed")
190
191
def on_open(ws):
192
print("Connection opened")
193
ws.send("Hello Server!")
194
195
ws = websocket.WebSocketApp("ws://echo.websocket.events",
196
on_open=on_open,
197
on_message=on_message,
198
on_error=on_error,
199
on_close=on_close)
200
ws.run_forever()
201
```
202
203
### Connection with Custom Headers and Authentication
204
205
```python
206
import websocket
207
208
def on_open(ws):
209
print("Authenticated connection established")
210
211
headers = {
212
"Authorization": "Bearer your-token-here",
213
"User-Agent": "MyApp/1.0"
214
}
215
216
ws = websocket.WebSocketApp("wss://api.example.com/websocket",
217
header=headers,
218
on_open=on_open)
219
ws.run_forever()
220
```
221
222
### Automatic Reconnection with External Dispatcher
223
224
```python
225
import websocket
226
import rel
227
228
def on_message(ws, message):
229
print(f"Market data: {message}")
230
231
def on_error(ws, error):
232
print(f"Connection error: {error}")
233
234
def on_close(ws, close_status_code, close_msg):
235
print("Connection closed, will reconnect...")
236
237
ws = websocket.WebSocketApp("wss://api.gemini.com/v1/marketdata/BTCUSD",
238
on_message=on_message,
239
on_error=on_error,
240
on_close=on_close)
241
242
# Run with automatic reconnection every 5 seconds
243
ws.run_forever(dispatcher=rel, reconnect=5)
244
rel.signal(2, rel.abort) # Handle Ctrl+C
245
rel.dispatch()
246
```
247
248
### Proxy Configuration
249
250
```python
251
import websocket
252
253
def on_open(ws):
254
print("Connected through proxy")
255
256
ws = websocket.WebSocketApp("ws://echo.websocket.events")
257
ws.run_forever(
258
http_proxy_host="proxy.company.com",
259
http_proxy_port=8080,
260
http_proxy_auth=("username", "password")
261
)
262
```
263
264
### SSL/TLS Configuration
265
266
```python
267
import websocket
268
import ssl
269
270
def on_open(ws):
271
print("Secure connection established")
272
273
sslopt = {
274
"cert_reqs": ssl.CERT_REQUIRED,
275
"ca_certs": "/path/to/ca-certificates.crt",
276
"certfile": "/path/to/client.crt",
277
"keyfile": "/path/to/client.key"
278
}
279
280
ws = websocket.WebSocketApp("wss://secure.example.com/websocket",
281
on_open=on_open)
282
ws.run_forever(sslopt=sslopt)
283
```
284
285
## Types
286
287
```python { .api }
288
# Callback function signatures
289
OnOpenCallback = Callable[[WebSocket], None]
290
OnReconnectCallback = Callable[[WebSocket], None]
291
OnMessageCallback = Callable[[WebSocket, Any], None]
292
OnErrorCallback = Callable[[WebSocket, Any], None]
293
OnCloseCallback = Callable[[WebSocket, Any, Any], None]
294
OnDataCallback = Callable[[WebSocket, Any, int, bool], None]
295
OnPingCallback = Callable[[WebSocket, str], None]
296
OnPongCallback = Callable[[WebSocket, str], None]
297
OnContMessageCallback = Callable[[WebSocket, Any, bool], None]
298
```