File: clients.rst

package info (click to toggle)
python-trio-websocket 0.12.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, trixie
  • size: 432 kB
  • sloc: python: 2,900; makefile: 41; sh: 17
file content (69 lines) | stat: -rw-r--r-- 2,153 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
.. _websocket-clients:

Clients
=======

.. currentmodule:: trio_websocket

Client Tutorial
---------------

This page goes into the details of creating a WebSocket client. Let's start by
revisiting the :ref:`client-example`.

.. code-block:: python
    :linenos:

    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
    <https://github.com/HyperionGray/trio-websocket/blob/master/examples/client.py>`__.

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.

.. autofunction:: open_websocket
    :async-with: ws

.. autofunction:: open_websocket_url
    :async-with: ws

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.

.. autofunction:: connect_websocket
.. autofunction:: connect_websocket_url

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.

.. autofunction:: wrap_client_stream