WebSocket class¶
The WebSocket class encapsulates a WebSocket
connection. MicroPie constructs an instance for each WebSocket
request and passes it as the first argument to your WebSocket handler.
Constructor¶
- class WebSocket(receive, send)¶
Create a new WebSocket wrapper around the ASGI
receiveandsendcallables. You do not instantiate this class yourself; MicroPie does so internally.
Methods¶
- accept(subprotocol=None, session_id=None)¶
Accept the WebSocket connection. You must call this method before sending or receiving messages. If you provide a session_id, MicroPie sets a
session_idcookie during the handshake. The optional subprotocol argument specifies a negotiated subprotocol.
- receive_text()¶
Await a text message from the client. Returns a string. Raises
ConnectionClosedif the client has disconnected. If the client sends bytes, MicroPie decodes them as UTF-8 (ignoring invalid sequences) and returns the decoded string.
- receive_bytes()¶
Await a binary message from the client. Returns bytes. Raises
ConnectionClosedif the client has disconnected. If the client sends text, MicroPie returns the UTF-8 encoded bytes.
- send_text(data)¶
Send a text message to the client. Raises
RuntimeErrorif you have not calledaccept().
- send_bytes(data)¶
Send a binary message to the client. Raises
RuntimeErrorif the connection has not been accepted.
- close(code=1000, reason=None)¶
Close the WebSocket connection. By default uses code 1000 (normal closure). The optional reason is sent to the client.
Attributes¶
- accepted¶
Trueif the WebSocket has been accepted.
- session_id¶
The session ID set during the handshake, or
Noneif not set.
Exceptions¶
MicroPie raises ConnectionClosed from
receive_text() and receive_bytes() when the client
disconnects. See Exceptions for exception details.