Clients

Client Tutorial

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import trio
from trio_websocket import open_websocket_url


async def main():
    try:
        async with open_websocket_url('wss://localhost/foo') as ws:
            await ws.send_message('hello world!')
            message = await ws.get_message()
            logging.info('Received message: %s', message)
    except OSError as ose:
        logging.error('Connection attempt failed: %s', ose)

trio.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, port, resource, *, use_ssl, subprotocols=None, extra_headers=None, message_queue_size=1, max_message_size=1048576, connect_timeout=60, disconnect_timeout=60) 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.

  • ssl.SSLContext] use_ssl (Union[bool,) – 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).

  • 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, ssl_context=None, *, subprotocols=None, extra_headers=None, message_queue_size=1, max_message_size=1048576, connect_timeout=60, disconnect_timeout=60) 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).

  • 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, host, port, resource, *, use_ssl, subprotocols=None, extra_headers=None, message_queue_size=1, max_message_size=1048576)

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.

  • ssl.SSLContext] use_ssl (Union[bool,) – 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).

Return type

WebSocketConnection

await trio_websocket.connect_websocket_url(nursery, url, ssl_context=None, *, subprotocols=None, extra_headers=None, message_queue_size=1, max_message_size=1048576)

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).

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, stream, host, resource, *, subprotocols=None, extra_headers=None, message_queue_size=1, max_message_size=1048576)

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).

Return type

WebSocketConnection