# Getting Started

## Installation

This library supports Python ≥3.5. The easiest installation method is to use PyPI.

    $ pip3 install trio-websocket

You can also install from source. Visit the project’s GitHub page, where you can clone the repository or download a Zip file. Change into the project directory and run the following command.

    $ pip3 install .

If you want to contribute to development of the library, also see Developer Installation.

## Client Example

This example briefly demonstrates how to create a WebSocket client.

     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)

The function `open_websocket_url()` is a context manager that automatically connects and performs the WebSocket handshake before entering the block. This ensures that the connection is usable before `ws.send_message(…)` is called. The context manager yields a `WebSocketConnection` instance that is used to send and receive messages. The context manager also closes the connection before exiting the block.

For more details and examples, see Clients.

## Server Example

This example briefly demonstrates how to create a WebSocket server. This server is an echo server, i.e. it responds to each incoming message by sending back an identical message.

     1import trio
     2from trio_websocket import serve_websocket, ConnectionClosed
     3
     4async def echo_server(request):
     5    ws = await request.accept()
     6    while True:
     7        try:
     8            message = await ws.get_message()
     9            await ws.send_message(message)
    10        except ConnectionClosed:
    11            break
    12
    13async def main():
    14    await serve_websocket(echo_server, '127.0.0.1', 8000, ssl_context=None)
    15
    16trio.run(main)

The function `serve_websocket()` requires a function that can handle each incoming connection. This handler function receives a `WebSocketRequest` object that the server can use to inspect the client’s handshake. Next, the server accepts the request in order to complete the handshake and receive a `WebSocketConnection` instance that can be used to send and receive messages.

For more details and examples, see Servers.