# Clients

## Client Tutorial

This page goes into the details of creating a WebSocket client. Let’s start by revisiting the Client Example.

     1import trio
     2from trio_websocket import open_websocket_url
     3
     4
     5async def main():
     6    try:
     7        async with open_websocket_url('wss://localhost/foo') as ws:
     8            await ws.send_message('hello world!')
     9            message = await ws.get_message()
    10            logging.info('Received message: %s', message)
    11    except OSError as ose:
    12        logging.error('Connection attempt failed: %s', ose)
    13
    14trio.run(main)

Note

A more complete example is included in the repository.

As explained in the tutorial, `open_websocket_url(…)` is a context manager that ensures the connection is properly opened and ready before entering the block. It also ensures that the connection is closed before exiting the block. This library contains two such context managers for creating client connections: one to connect by host and one to connect by URL.

async with trio_websocket.open_websocket(host: str, port: int, resource: str, *, use_ssl: bool | ssl.SSLContext, subprotocols: Iterable[str] | None = None, extra_headers: list[tuple[bytes, bytes]] | None = None, message_queue_size: int = 1, max_message_size: int = 1048576, receive_buffer_size: None | int = 4096, connect_timeout: float = 60, disconnect_timeout: float = 60) → AsyncGenerator[WebSocketConnection, None] as ws

  Open a WebSocket client connection to a host.

  This async context manager connects when entering the context manager and disconnects when exiting. It yields a `WebSocketConnection` instance.

  Parameters:

    - host (str) – The host to connect to.

    - port (int) – The port to connect to.

    - resource (str) – The resource, i.e. URL path.

    - use_ssl (Union[bool, ssl.SSLContext]) – If this is an SSL context, then use that context. If this is `True` then use default SSL context. If this is `False` then disable SSL.

    - subprotocols – An iterable of strings representing preferred subprotocols.

    - extra_headers (list[tuple[bytes,bytes]]) – A list of 2-tuples containing HTTP header key/value pairs to send with the connection request. Note that headers used by the WebSocket protocol (e.g. `Sec-WebSocket-Accept`) will be overwritten.

    - message_queue_size (int) – The maximum number of messages that will be buffered in the library’s internal message queue.

    - max_message_size (int) – The maximum message size as measured by `len()`. If a message is received that is larger than this size, then the connection is closed with code 1009 (Message Too Big).

    - receive_buffer_size (Optional[int]) – The buffer size we use to receive messages internally. None to let trio choose. Defaults to 4 KiB.

    - connect_timeout (float) – The number of seconds to wait for the connection before timing out.

    - disconnect_timeout (float) – The number of seconds to wait when closing the connection before timing out.

  Raises:

    HandshakeError – for any networking error, client-side timeout (`ConnectionTimeout`, `DisconnectionTimeout`), or server rejection (`ConnectionRejected`) during handshakes.

async with trio_websocket.open_websocket_url(url: str, ssl_context: ssl.SSLContext | None = None, *, subprotocols: Iterable[str] | None = None, extra_headers: list[tuple[bytes, bytes]] | None = None, message_queue_size: int = 1, max_message_size: int = 1048576, connect_timeout: float = 60, disconnect_timeout: float = 60, receive_buffer_size: None | int = 4096) → AbstractAsyncContextManager[WebSocketConnection] as ws

  Open a WebSocket client connection to a URL.

  This async context manager connects when entering the context manager and disconnects when exiting. It yields a `WebSocketConnection` instance.

  Parameters:

    - url (str) – A WebSocket URL, i.e. ws: or wss: URL scheme.

    - ssl_context (ssl.SSLContext or None) – Optional SSL context used for `wss:` URLs. A default SSL context is used for `wss:` if this argument is `None`.

    - subprotocols – An iterable of strings representing preferred subprotocols.

    - extra_headers (list[tuple[bytes,bytes]]) – A list of 2-tuples containing HTTP header key/value pairs to send with the connection request. Note that headers used by the WebSocket protocol (e.g. `Sec-WebSocket-Accept`) will be overwritten.

    - message_queue_size (int) – The maximum number of messages that will be buffered in the library’s internal message queue.

    - max_message_size (int) – The maximum message size as measured by `len()`. If a message is received that is larger than this size, then the connection is closed with code 1009 (Message Too Big).

    - receive_buffer_size (Optional[int]) – The buffer size we use to receive messages internally. None to let trio choose. Defaults to 4 KiB.

    - connect_timeout (float) – The number of seconds to wait for the connection before timing out.

    - disconnect_timeout (float) – The number of seconds to wait when closing the connection before timing out.

  Raises:

    HandshakeError – for any networking error, client-side timeout (`ConnectionTimeout`, `DisconnectionTimeout`), or server rejection (`ConnectionRejected`) during handshakes.

## Custom Nursery

The two context managers above create an internal nursery to run background tasks. If you wish to specify your own nursery instead, you should use the the following convenience functions instead.

await trio_websocket.connect_websocket(nursery: trio.Nursery, host: str, port: int, resource: str, *, use_ssl: bool | ssl.SSLContext, subprotocols: Iterable[str] | None = None, extra_headers: list[tuple[bytes, bytes]] | None = None, message_queue_size: int = 1, max_message_size: int = 1048576, receive_buffer_size: None | int = 4096) → WebSocketConnection

  Return an open WebSocket client connection to a host.

  This function is used to specify a custom nursery to run connection background tasks in. The caller is responsible for closing the connection.

  If you don’t need a custom nursery, you should probably use `open_websocket()` instead.

  Parameters:

    - nursery – A Trio nursery to run background tasks in.

    - host (str) – The host to connect to.

    - port (int) – The port to connect to.

    - resource (str) – The resource, i.e. URL path.

    - use_ssl (Union[bool, ssl.SSLContext]) – If this is an SSL context, then use that context. If this is `True` then use default SSL context. If this is `False` then disable SSL.

    - subprotocols – An iterable of strings representing preferred subprotocols.

    - extra_headers (list[tuple[bytes,bytes]]) – A list of 2-tuples containing HTTP header key/value pairs to send with the connection request. Note that headers used by the WebSocket protocol (e.g. `Sec-WebSocket-Accept`) will be overwritten.

    - message_queue_size (int) – The maximum number of messages that will be buffered in the library’s internal message queue.

    - max_message_size (int) – The maximum message size as measured by `len()`. If a message is received that is larger than this size, then the connection is closed with code 1009 (Message Too Big).

    - receive_buffer_size (Optional[int]) – The buffer size we use to receive messages internally. None to let trio choose. Defaults to 4 KiB.

  Return type:

    WebSocketConnection

await trio_websocket.connect_websocket_url(nursery: trio.Nursery, url: str, ssl_context: ssl.SSLContext | None = None, *, subprotocols: Iterable[str] | None = None, extra_headers: list[tuple[bytes, bytes]] | None = None, message_queue_size: int = 1, max_message_size: int = 1048576, receive_buffer_size: None | int = 4096) → WebSocketConnection

  Return an open WebSocket client connection to a URL.

  This function is used to specify a custom nursery to run connection background tasks in. The caller is responsible for closing the connection.

  If you don’t need a custom nursery, you should probably use `open_websocket_url()` instead.

  Parameters:

    - nursery – A nursery to run background tasks in.

    - url (str) – A WebSocket URL.

    - ssl_context (ssl.SSLContext or None) – Optional SSL context used for `wss:` URLs.

    - subprotocols – An iterable of strings representing preferred subprotocols.

    - extra_headers (list[tuple[bytes,bytes]]) – A list of 2-tuples containing HTTP header key/value pairs to send with the connection request. Note that headers used by the WebSocket protocol (e.g. `Sec-WebSocket-Accept`) will be overwritten.

    - message_queue_size (int) – The maximum number of messages that will be buffered in the library’s internal message queue.

    - max_message_size (int) – The maximum message size as measured by `len()`. If a message is received that is larger than this size, then the connection is closed with code 1009 (Message Too Big).

    - receive_buffer_size (Optional[int]) – The buffer size we use to receive messages internally. None to let trio choose. Defaults to 4 KiB.

  Return type:

    WebSocketConnection

## Custom Stream

The WebSocket protocol is defined as an application layer protocol that runs on top of TCP, and the convenience functions described above automatically create those TCP connections. In more obscure use cases, you might want to run the WebSocket protocol on top of some other type of transport protocol. The library includes a convenience function that allows you to wrap any arbitrary Trio stream with a client WebSocket.

await trio_websocket.wrap_client_stream(nursery: trio.Nursery, stream: trio.SocketStream | trio.SSLStream[trio.SocketStream], host: str, resource: str, *, subprotocols: Iterable[str] | None = None, extra_headers: list[tuple[bytes, bytes]] | None = None, message_queue_size: int = 1, max_message_size: int = 1048576, receive_buffer_size: None | int = 4096) → WebSocketConnection

  Wrap an arbitrary stream in a WebSocket connection.

  This is a low-level function only needed in rare cases. In most cases, you should use `open_websocket()` or `open_websocket_url()`.

  Parameters:

    - nursery – A Trio nursery to run background tasks in.

    - stream (trio.abc.Stream) – A Trio stream to be wrapped.

    - host (str) – A host string that will be sent in the `Host:` header.

    - resource (str) – A resource string, i.e. the path component to be accessed on the server.

    - subprotocols – An iterable of strings representing preferred subprotocols.

    - extra_headers (list[tuple[bytes,bytes]]) – A list of 2-tuples containing HTTP header key/value pairs to send with the connection request. Note that headers used by the WebSocket protocol (e.g. `Sec-WebSocket-Accept`) will be overwritten.

    - message_queue_size (int) – The maximum number of messages that will be buffered in the library’s internal message queue.

    - max_message_size (int) – The maximum message size as measured by `len()`. If a message is received that is larger than this size, then the connection is closed with code 1009 (Message Too Big).

    - receive_buffer_size (Optional[int]) – The buffer size we use to receive messages internally. None to let trio choose. Defaults to 4 KiB.

  Return type:

    WebSocketConnection