Handles the opening handshake, frame encoding/decoding, masking
(client→server frames MUST be masked per RFC 6455 §5.3), and
automatic PONG replies to PING frames.
This type is Movable but not Copyable. It supports the context
manager protocol (__enter__ / __exit__) for use with with.
Fields:
_stream: Underlying transport (TLS or TCP).
_key: The Sec-WebSocket-Key used for this connection.
Example:
with WsClient.connect("wss://echo.websocket.events") as ws:
ws.send_text("hello")
var msg = ws.recv_message()
print(msg.as_text())
connect
def connect(url: String) -> Self
Connect to a WebSocket server using default TLS configuration.
Equivalent to WsClient.connect(url, TlsConfig()).
- Args
url: WebSocket URL (ws:// or wss://).
Raises NetworkError: If the TCP/TLS connection fails.
WsHandshakeError: If the server's Upgrade response is invalid.
def connect(url: String, config: TlsConfig) -> Self
Connect to a WebSocket server with custom TLS configuration.
For wss:// URLs, wraps the connection in TLS using config.
- Args
url: WebSocket URL (ws:// or wss://).config: TLS configuration (only used for wss://).
Raises NetworkError: If the TCP/TLS connection fails.
WsHandshakeError: If the server's Upgrade response is invalid or
Sec-WebSocket-Accept does not match.
send_text
def send_text(self, msg: String)
Send a UTF-8 text message (client→server, masked).
- Args
msg: The message string. Must be valid UTF-8.
Raises NetworkError: On I/O failure.
recv_message
def recv_message(mut self) -> WsMessage
Receive the next complete message as a WsMessage.
A higher-level alternative to recv() that returns a
WsMessage (Text or Binary) instead of a raw WsFrame.
A fragmented message (a TEXT or BINARY frame without FIN followed
by CONTINUATION frames up to one with FIN, RFC 6455 sec 5.4) is
reassembled and returned whole. PING frames are handled
transparently (PONG sent automatically), PONG frames are skipped,
and either may arrive between fragments. CLOSE frames raise a
NetworkError. A text message is checked for valid UTF-8 as a
whole, so a code point may be split across fragments. The
reassembled payload is bounded by max_frame_size.
Example:
var msg = ws.recv_message()
if msg.is_text:
print(msg.as_text())
Raises NetworkError: If a CLOSE frame is received or I/O fails.
WsProtocolError: On protocol violation: a CONTINUATION with no
message to continue, a new data frame inside a fragmented
message, an unknown data opcode, invalid UTF-8 in a text
message, or a message over max_frame_size (CLOSE 1009
is sent first).