# API

In addition to the convenience functions documented in Clients and Servers, the API has several important classes described on this page.

## Requests

class trio_websocket.WebSocketRequest

  A request object presents the client’s handshake to a server handler. The server can inspect handshake properties like HTTP headers, subprotocols, etc. The server can also set some handshake properties like subprotocol. The server should call `accept()` to complete the handshake and obtain a connection object.

  headers

    HTTP headers represented as a list of (name, value) pairs.

    Return type:

      list[tuple]

  proposed_subprotocols

    A tuple of protocols proposed by the client.

    Return type:

      tuple[str]

  local

    The connection’s local endpoint.

    Return type:

      Endpoint or str

  remote

    The connection’s remote endpoint.

    Return type:

      Endpoint or str

  await accept(*, subprotocol: str | None = None, extra_headers: list[tuple[bytes, bytes]] | None = None) → WebSocketConnection

    Accept the request and return a connection object.

    Parameters:

      - subprotocol (str or None) – The selected subprotocol for this connection.

      - extra_headers (list[tuple[bytes,bytes]] or None) – A list of 2-tuples containing key/value pairs to send as HTTP headers.

    Return type:

      WebSocketConnection

  await reject(status_code: int, *, extra_headers: list[tuple[bytes, bytes]] | None = None, body: bytes | None = None) → None

    Reject the handshake.

    Parameters:

      - status_code (int) – The 3 digit HTTP status code. In order to be RFC-compliant, this should NOT be 101, and would ideally be an appropriate code in the range 300-599.

      - extra_headers (list[tuple[bytes,bytes]]) – A list of 2-tuples containing key/value pairs to send as HTTP headers.

      - body (bytes or None) – If provided, this data will be sent in the response body, otherwise no response body will be sent.

## Connections

class trio_websocket.WebSocketConnection

  A connection object has functionality for sending and receiving messages, pinging the remote endpoint, and closing the WebSocket.

  Note

  The preferred way to obtain a connection is to use one of the convenience functions described in Clients or Servers. Instantiating a connection instance directly is tricky and is not recommended.

  This object has properties that expose connection metadata.

  closed

    (Read-only) The reason why the connection was or is being closed, else `None`.

    Return type:

      Optional[CloseReason]

  is_client

    (Read-only) Is this a client instance?

  is_server

    (Read-only) Is this a server instance?

  local

    The local endpoint of the connection.

    Return type:

      Endpoint or str

  remote

    The remote endpoint of the connection.

    Return type:

      Endpoint or str

  This object exposes the following properties related to the WebSocket handshake.

  path

    The requested URL path. For clients, this is set when the connection is instantiated. For servers, it is set after the handshake completes.

    Return type:

      str or None

  subprotocol

    (Read-only) The negotiated subprotocol, or `None` if there is no subprotocol.

    This is only valid after the opening handshake is complete.

    Return type:

      str or None

  handshake_headers

    The HTTP headers that were sent by the remote during the handshake, stored as 2-tuples containing key/value pairs. Header keys are always lower case.

    Return type:

      tuple[tuple[str,str]]

  A connection object has a pair of methods for sending and receiving WebSocket messages. Messages can be `str` or `bytes` objects.

  await send_message(message: str | bytes) → None

    Send a WebSocket message.

    Parameters:

      message (str or bytes) – The message to send.

    Raises:

      ConnectionClosed – if connection is closed, or being closed

  await get_message() → str | bytes

    Receive the next WebSocket message.

    If no message is available immediately, then this function blocks until a message is ready.

    If the remote endpoint closes the connection, then the caller can still get messages sent prior to closing. Once all pending messages have been retrieved, additional calls to this method will raise `ConnectionClosed`. If the local endpoint closes the connection, then pending messages are discarded and calls to this method will immediately raise `ConnectionClosed`.

    Return type:

      str or bytes

    Raises:

      ConnectionClosed – if the connection is closed.

  A connection object also has methods for sending pings and pongs. Each ping is sent with a unique payload, and the function blocks until a corresponding pong is received from the remote endpoint. This feature can be used to implement a bidirectional heartbeat.

  A pong, on the other hand, sends an unsolicited pong to the remote endpoint and does not expect or wait for a response. This feature can be used to implement a unidirectional heartbeat.

  await ping(payload: bytes | None = None) → None

    Send WebSocket ping to remote endpoint and wait for a correspoding pong.

    Each in-flight ping must include a unique payload. This function sends the ping and then waits for a corresponding pong from the remote endpoint.

    Note: If the remote endpoint recieves multiple pings, it is allowed to send a single pong. Therefore, the order of calls to ``ping()`` is tracked, and a pong will wake up its corresponding ping as well as all previous in-flight pings.

    Parameters:

      payload (bytes or None) – The payload to send. If `None` then a random 32-bit payload is created.

    Raises:

      - ConnectionClosed – if connection is closed.

      - ValueError – if `payload` is identical to another in-flight ping.

  await pong(payload: bytes | None = None) → None

    Send an unsolicted pong.

    Parameters:

      payload (bytes or None) – The pong’s payload. If `None`, then no payload is sent.

    Raises:

      ConnectionClosed – if connection is closed

  Finally, the socket offers a method to close the connection. The connection context managers in Clients and Servers will automatically close the connection for you, but you may want to close the connection explicity if you are not using a context manager or if you want to customize the close reason.

  await aclose(code: int = 1000, reason: str | None = None) → None

    Close the WebSocket connection.

    This sends a closing frame and suspends until the connection is closed. After calling this method, any further I/O on this WebSocket (such as `get_message()` or `send_message()`) will raise `ConnectionClosed`.

    This method is idempotent: it may be called multiple times on the same connection without any errors.

    Parameters:

      - code (int) – A 4-digit code number indicating the type of closure.

      - reason (str) – An optional string describing the closure.

class trio_websocket.CloseReason(code: int, reason: str | None)

  Contains information about why a WebSocket was closed.

  property code: int

    (Read-only) The numeric close code.

  property name: str

    (Read-only) The human-readable close code.

  property reason: str | None

    (Read-only) An arbitrary reason string.

exception trio_websocket.ConnectionClosed(reason: CloseReason | None)

  A WebSocket operation cannot be completed because the connection is closed or in the process of closing.

exception trio_websocket.HandshakeError

  There was an error during connection or disconnection with the websocket server.

exception trio_websocket.ConnectionRejected(status_code: int, headers: tuple[tuple[bytes, bytes], ...], body: bytes | None)

  Bases: `HandshakeError`

  A WebSocket connection could not be established because the server rejected the connection attempt.

exception trio_websocket.ConnectionTimeout

  Bases: `HandshakeError`

  There was a timeout when connecting to the websocket server.

exception trio_websocket.DisconnectionTimeout

  Bases: `HandshakeError`

  There was a timeout when disconnecting from the websocket server.

## Utilities

These are classes that you do not need to instantiate yourself, but you may get access to instances of these classes through other APIs.

class trio_websocket.Endpoint(address: str | int, port: int, is_ssl: bool)

  Represents a connection endpoint.

  address

    IP address `ipaddress.ip_address`

  is_ssl

    Whether SSL is in use

  port

    TCP port

  property url: str

    Return a URL representation of a TCP endpoint, e.g. `ws://127.0.0.1:80`.