Server (trio)¶
The trio API is experimental.
Please provide feedback in GitHub issues about the API, especially if you can propose a more intuitive or convenient way to start and stop a server.
Creating a server¶
- await websockets.trio.server.serve(handler, port=None, *, host=None, backlog=None, listeners=None, ssl=None, origins=None, extensions=None, subprotocols=None, select_subprotocol=None, compression='deflate', process_request=None, process_response=None, server_header='Python/3.14 websockets/17.0', open_timeout=10, ping_interval=20, ping_timeout=20, close_timeout=10, max_size=1048576, max_queue=16, logger=None, create_connection=None, task_status=TASK_STATUS_IGNORED)¶
Create a WebSocket server listening on
port.Whenever a client connects, the server creates a
ServerConnection, performs the opening handshake, and delegates to thehandlercoroutine.The handler receives the
ServerConnectioninstance, which you can use to send and receive messages.Once the handler completes, either normally or with an exception, the server performs the closing handshake and closes the connection.
When using
serve()withnursery.start, you get back aServerobject. Treat it as an asynchronous context manager to ensure that the server will be closed gracefully:from websockets.trio.server import serve async def handler(websocket): ... # set this event to exit the server stop = trio.Event() with trio.open_nursery() as nursery: server = await nursery.start(serve, handler, port) async with server: await stop.wait()
Alternatively, to stop the server gracefully, call its
aclose()method:with trio.open_nursery() as nursery: server = await nursery.start(serve, handler, port) try: await stop.wait() finally: await server.aclose()
- Parameters:
handler – Connection handler. It receives the WebSocket connection, which is a
ServerConnection, in argument.port – TCP port the server listens on. See
open_tcp_listeners()for details.host – Network interfaces the server binds to. See
open_tcp_listeners()for details.backlog – Listen backlog. See
open_tcp_listeners()for details.listeners – Preexisting TCP listeners.
listenersreplacesport,host, andbacklog. Seetrio.serve_listeners()for details.ssl – Configuration for enabling TLS on the connection.
origins – Acceptable values of the
Originheader, for defending against Cross-Site WebSocket Hijacking attacks. Values can bestrto test for an exact match or regular expressions compiled byre.compile()to test against a pattern. IncludeNonein the list if the lack of an origin is acceptable.extensions – List of supported extensions, in order in which they should be negotiated and run.
subprotocols – List of supported subprotocols, in order of decreasing preference.
select_subprotocol – Callback for selecting a subprotocol among those supported by the client and the server. It receives a
ServerConnection(not aServerProtocol!) instance and a list of subprotocols offered by the client. Other than the first argument, it has the same behavior as theServerProtocol.select_subprotocolmethod.compression – The “permessage-deflate” extension is enabled by default. Set
compressiontoNoneto disable it. See the compression guide for details.process_request – Intercept the request during the opening handshake. Return an HTTP response to force the response or
Noneto continue normally. When you force an HTTP 101 Continue response, the handshake is successful. Else, the connection is aborted.process_requestmay be a function or a coroutine.process_response – Intercept the response during the opening handshake. Return an HTTP response to force the response or
Noneto continue normally. When you force an HTTP 101 Continue response, the handshake is successful. Else, the connection is aborted.process_responsemay be a function or a coroutine.server_header – Value of the
Serverresponse header. It defaults to"Python/x.y.z websockets/X.Y". Setting it toNoneremoves the header.open_timeout – Timeout for opening connections in seconds.
Nonedisables the timeout.ping_interval – Interval between keepalive pings in seconds.
Nonedisables keepalive.ping_timeout – Timeout for keepalive pings in seconds.
Nonedisables timeouts.close_timeout – Timeout for closing connections in seconds.
Nonedisables the timeout.max_size – Maximum size of incoming messages in bytes.
Nonedisables the limit. You may pass a(max_message_size, max_fragment_size)tuple to set different limits for messages and fragments when you expect long messages sent in short fragments.max_queue – High-water mark of the buffer where frames are received. It defaults to 16 frames. The low-water mark defaults to
max_queue // 4. You may pass a(high, low)tuple to set the high-water and low-water marks. If you want to disable flow control entirely, you may set it toNone, although that’s a bad idea.logger – Logger for this server. It defaults to
logging.getLogger("websockets.server"). See the logging guide for details.create_connection – Factory for the
ServerConnectionmanaging the connection. Set it to a wrapper or a subclass to customize connection handling.task_status – For compatibility with
nursery.start.
unix_serve is not available in the Trio implementation.
This is because Trio does not provide open_unix_listeners yet.
Instead, you can create Trio listeners using Unix domain sockets then
call serve() with a listeners arguments.
Routing connections¶
- await websockets.trio.router.route(url_map, *args, server_name=None, ssl=None, create_router=None, task_status=TASK_STATUS_IGNORED, **kwargs)¶
Create a WebSocket server dispatching connections to different handlers.
This feature requires the third-party library werkzeug:
$ pip install werkzeug
route()accepts the same arguments asserve(), except as described below.The first argument is a
werkzeug.routing.Mapthat maps URL patterns to connection handlers. In addition to the connection, handlers receive parameters captured in the URL as keyword arguments.Here’s an example:
from websockets.trio.router import route from werkzeug.routing import Map, Rule async def channel_handler(websocket, channel_id): ... url_map = Map([ Rule("/channel/<uuid:channel_id>", endpoint=channel_handler), ... ]) # set this event to exit the server stop = trio.Event() with trio.open_nursery() as nursery: server = await nursery.start(route, url_map, ...) async with server: await stop.wait()
Refer to the documentation of
werkzeug.routingfor details.If you define redirects with
Rule(..., redirect_to=...)in the URL map, when the server runs behind a reverse proxy that modifies theHostheader or terminates TLS, you need additional configuration:Set
server_nameto the name of the server as seen by clients. When not provided, websockets uses the value of theHostheader.Set
ssl=Trueto generatewss://URIs without enabling TLS. Under the hood, this bind the URL map with aurl_schemeofwss://instead ofws://.
There is no need to specify
websocket=Truein each rule. It is added automatically.- Parameters:
url_map – Mapping of URL patterns to connection handlers.
server_name – Name of the server as seen by clients. If
None, websockets uses the value of theHostheader.ssl – Configuration for enabling TLS on the connection. Set it to
Trueif a reverse proxy terminates TLS connections.create_router – Factory for the
Routerdispatching requests to handlers. Set it to a wrapper or a subclass to customize routing.task_status – For compatibility with
nursery.start.
unix_route is not available in the Trio implementation.
This is because unix_serve isn’t available either, as explained above.
Running a server¶
- class websockets.trio.server.Server(listeners, handler, logger=None)¶
WebSocket server returned by
serve().- Parameters:
listeners (list[trio.SocketListener]) – List of Trio listeners accepting new connections.
handler (Callable[[trio.abc.Stream], Awaitable[None]]) – Handler for one connection. It receives a Trio stream.
logger (LoggerLike | None) – Logger for this server. It defaults to
logging.getLogger("websockets.server"). See the logging guide for details.
- connections¶
Set of active connections.
This property contains all connections that completed the opening handshake successfully and didn’t start the closing handshake yet. It can be useful in combination with
broadcast().
- await aclose(close_connections=True, code=CloseCode.GOING_AWAY, reason='')¶
Close the server.
Close the TCP listeners.
When
close_connectionsisTrue, which is the default, close existing connections. Specifically:Reject opening WebSocket connections with an HTTP 503 (service unavailable) error. This happens when the server accepted the TCP connection but didn’t complete the opening handshake before closing.
Close open WebSocket connections with close code 1001 (going away).
codeandreasoncan be customized, for example to use code 1012 (service restart).
Wait until all connection handlers have returned.
aclose()is idempotent.
- listeners¶
Using a connection¶
- class websockets.trio.server.ServerConnection(nursery, stream, protocol, server, *, ping_interval=20, ping_timeout=20, close_timeout=10, max_queue=16)¶
trioimplementation of a WebSocket server connection.ServerConnectionprovidesrecv()andsend()methods for receiving and sending messages.It supports asynchronous iteration to receive messages:
async for message in websocket: await process(message)
The iterator exits normally when the connection is closed with close code 1000 (OK) or 1001 (going away) or without a close code. It raises a
ConnectionClosedErrorwhen the connection is closed with any other code.The
ping_interval,ping_timeout,close_timeout, andmax_queuearguments have the same meaning as inserve().- Parameters:
nursery (trio.Nursery) – Trio nursery.
stream (trio.abc.Stream) – Trio stream connected to a WebSocket client.
protocol (ServerProtocol) – Sans-I/O connection.
server (Server) – Server that manages this connection.
- respond(status, text)¶
Create a plain text HTTP response.
process_requestandprocess_responsemay call this method to return an HTTP response instead of performing the WebSocket opening handshake.You can modify the response before returning it, for example by changing HTTP headers.
- Parameters:
status – HTTP status code.
text – HTTP response body; it will be encoded to UTF-8.
- Returns:
HTTP response to send to the client.
- async for ... in __aiter__()¶
Iterate on incoming messages.
The iterator calls
recv()and yields messages asynchronously in an infinite loop.It exits when the connection is closed normally. It raises a
ConnectionClosedErrorexception after a protocol error or a network failure.
- await recv(decode=None)¶
Receive the next message.
When the connection is closed,
recv()raisesConnectionClosed. Specifically, it raisesConnectionClosedOKafter a normal closure andConnectionClosedErrorafter a protocol error or a network failure. This is how you detect the end of the message stream.Canceling
recv()is safe. There’s no risk of losing data. The next invocation ofrecv()will return the next message.This makes it possible to enforce a timeout by wrapping
recv()inmove_on_after()orfail_after().When the message is fragmented,
recv()waits until all fragments are received, reassembles them, and returns the whole message.- Parameters:
decode – Set this flag to override the default behavior of returning
strorbytes. See below for details.- Returns:
A string (
str) for a Text frame or a bytestring (bytes) for a Binary frame.You may override this behavior with the
decodeargument:Set
decode=Falseto disable UTF-8 decoding of Text frames and return a bytestring (bytes). This improves performance when decoding isn’t needed, for example if the message contains JSON and you’re using a JSON library that expects a bytestring.Set
decode=Trueto force UTF-8 decoding of Binary frames and return a string (str). This may be useful for servers that send binary frames instead of text frames.
- Raises:
ConnectionClosed – When the connection is closed.
ConcurrencyError – If two coroutines call
recv()orrecv_streaming()concurrently.
- async for ... in recv_streaming(decode=None)¶
Receive the next message frame by frame.
This method is designed for receiving fragmented messages. It returns an asynchronous iterator that yields each fragment as it is received. This iterator must be fully consumed. Else, future calls to
recv()orrecv_streaming()will raiseConcurrencyError, making the connection unusable.recv_streaming()raises the same exceptions asrecv().Canceling
recv_streaming()before receiving the first frame is safe. Canceling it after receiving one or more frames leaves the iterator in a partially consumed state, making the connection unusable. Instead, you should close the connection withaclose().- Parameters:
decode – Set this flag to override the default behavior of returning
strorbytes. See below for details.- Returns:
An iterator of strings (
str) for a Text frame or bytestrings (bytes) for a Binary frame.You may override this behavior with the
decodeargument:Set
decode=Falseto disable UTF-8 decoding of Text frames and return bytestrings (bytes). This may be useful to optimize performance when decoding isn’t needed.Set
decode=Trueto force UTF-8 decoding of Binary frames and return strings (str). This is useful for servers that send binary frames instead of text frames.
- Raises:
ConnectionClosed – When the connection is closed.
ConcurrencyError – If two coroutines call
recv()orrecv_streaming()concurrently.
- await send(message, *, text=None)¶
Send a message.
A string (
str) is sent as a Text frame. A bytestring or bytes-like object (bytes,bytearray, ormemoryview) is sent as a Binary frame.You may override this behavior with the
textargument:Set
text=Trueto send an UTF-8 bytestring or bytes-like object (bytes,bytearray, ormemoryview) in a Text frame. This improves performance when the message is already UTF-8 encoded, for example if the message contains JSON and you’re using a JSON library that produces a bytestring.Set
text=Falseto send a string (str) in a Binary frame. This may be useful for servers that expect binary frames instead of text frames.
send()also accepts an iterable or asynchronous iterable of strings, bytestrings, or bytes-like objects to enable fragmentation. Each item is treated as a message fragment and sent in its own frame. All items must be of the same type, or elsesend()will raise aTypeErrorand the connection will be closed.send()rejects dict-like objects because this is often an error. (If you really want to send the keys of a dict-like object as fragments, call itskeys()method and pass the result tosend().)Canceling
send()is discouraged. Instead, you should close the connection withaclose(). Indeed, there are only two situations wheresend()may yield control to the event loop and then get canceled; in both cases,aclose()has the same effect and is more clear:The write buffer is full. If you don’t want to wait until enough data is sent, your only alternative is to close the connection.
aclose()will likely time out then abort the TCP connection.messageis an asynchronous iterator that yields control. Stopping in the middle of a fragmented message will cause a protocol error and the connection will be closed.
When the connection is closed,
send()raisesConnectionClosed. Specifically, it raisesConnectionClosedOKafter a normal connection closure andConnectionClosedErrorafter a protocol error or a network failure.- Parameters:
- Raises:
ConnectionClosed – When the connection is closed.
TypeError – If
messagedoesn’t have a supported type.
- await aclose(code=CloseCode.NORMAL_CLOSURE, reason='')¶
Perform the closing handshake.
aclose()waits for the other end to complete the handshake and for the TCP connection to terminate.aclose()is idempotent: it doesn’t do anything once the connection is closed.- Parameters:
code – WebSocket close code.
reason – WebSocket close reason.
- await wait_closed()¶
Wait until the connection is closed.
wait_closed()waits for the closing handshake to complete and for the TCP connection to terminate.
- await ping(data=None, *, ack_on_close=False)¶
Send a Ping.
A ping may serve as a keepalive or as a check that the remote endpoint received all messages up to this point
- Parameters:
data – Payload of the ping. A
strwill be encoded to UTF-8. IfdataisNone, the payload is four random bytes.ack_on_close – when this option is
True, the event will also be set when the connection is closed. While this avoids getting stuck waiting for a pong that will never arrive, it requires checking that the state of the connection is stillOPENto confirm that a pong was received, rather than the connection being closed.
- Returns:
An event that will be set when the corresponding pong is received. You can ignore it if you don’t intend to wait.
pong_received = await ws.ping() # only if you want to wait for the corresponding pong await pong_received.wait()
- Raises:
ConnectionClosed – When the connection is closed.
ConcurrencyError – If another ping was sent with the same data and the corresponding pong wasn’t received yet.
- await pong(data=b'')¶
Send a Pong.
An unsolicited pong may serve as a unidirectional heartbeat.
- Parameters:
data – Payload of the pong. A
strwill be encoded to UTF-8.- Raises:
ConnectionClosed – When the connection is closed.
WebSocket connection objects also provide these attributes:
- logger: Logger | LoggerAdapter[Any]¶
Logger for this connection.
- property local_address: Any¶
Local address of the connection.
For IPv4 connections, this is a
(host, port)tuple.The format of the address depends on the address family. See
getsockname().
- property remote_address: Any¶
Remote address of the connection.
For IPv4 connections, this is a
(host, port)tuple.The format of the address depends on the address family. See
getpeername().
- latency: float¶
Latency of the connection, in seconds.
Latency is defined as the round-trip time of the connection. It is measured by sending a Ping frame and waiting for a matching Pong frame. Before the first measurement,
latencyis0.By default, websockets enables a keepalive mechanism that sends Ping frames automatically at regular intervals. You can also send Ping frames and measure latency with
ping().
- property state: State¶
State of the WebSocket connection, defined in RFC 6455.
This attribute is provided for completeness. Typical applications shouldn’t check its value. Instead, they should call
recv()orsend()and handleConnectionClosedexceptions.
The following attributes are available after the opening handshake, once the WebSocket connection is open:
- property subprotocol: Subprotocol | None¶
Subprotocol negotiated during the opening handshake.
Noneif no subprotocol was negotiated.
The following attributes are available after the closing handshake, once the WebSocket connection is closed:
- property close_code: int | None¶
State of the WebSocket connection, defined in RFC 6455.
This attribute is provided for completeness. Typical applications shouldn’t check its value. Instead, they should inspect attributes of
ConnectionClosedexceptions.
- property close_reason: str | None¶
State of the WebSocket connection, defined in RFC 6455.
This attribute is provided for completeness. Typical applications shouldn’t check its value. Instead, they should inspect attributes of
ConnectionClosedexceptions.
Broadcast¶
- await websockets.trio.server.broadcast(connections, message, *, raise_exceptions=False, text=None)¶
Broadcast a message to several WebSocket connections.
A string (
str) is sent as a Text frame. A bytestring or bytes-like object (bytes,bytearray, ormemoryview) is sent as a Binary frame.You may override this behavior with the
textargument:Set
text=Trueto send an UTF-8 bytestring or bytes-like object (bytes,bytearray, ormemoryview) in a Text frame. This improves performance when the message is already UTF-8 encoded, for example if the message contains JSON and you’re using a JSON library that produces a bytestring.Set
text=Falseto send a string (str) in a Binary frame. This may be useful for servers that expect binary frames instead of text frames.
broadcast()is equivalent to callingsend()for each connection. It returns when all messages have been sent.Unlike
send(),broadcast()doesn’t support sending fragmented messages. Indeed, fragmentation is useful for sending large messages without buffering them in memory, whilebroadcast()buffers one copy per connection as fast as possible.broadcast()skips connections that aren’t open in order to avoid errors on connections where the closing handshake is in progress.broadcast()ignores failures to write the message on some connections. It continues writing to other connections. You may setraise_exceptionstoTrueto record failures and raise all exceptions in a PEP 654ExceptionGroup.While
broadcast()makes more sense for servers, it works identically with clients, if you have a use case for opening connections to many servers and broadcasting a message to them.
HTTP Basic Authentication¶
websockets supports HTTP Basic Authentication according to RFC 7235 and RFC 7617.
- websockets.trio.server.basic_auth(realm='', credentials=None, check_credentials=None)¶
Factory for
process_requestto enforce HTTP Basic Authentication.basic_auth()is designed to integrate withserve()as follows:from websockets.asyncio.server import basic_auth, serve async with serve( ..., process_request=basic_auth( realm="my dev server", credentials=("hello", "iloveyou"), ), ):
If authentication succeeds, the connection’s
usernameattribute is set. If it fails, the server responds with an HTTP 401 Unauthorized status.One of
credentialsorcheck_credentialsmust be provided; not both.- Parameters:
realm – Scope of protection. It should contain only ASCII characters because the encoding of non-ASCII characters is undefined. Refer to section 2.2 of RFC 7235 for details.
credentials – Hard coded authorized credentials. It can be a
(username, password)pair or a list of such pairs.check_credentials – Function or coroutine that verifies credentials. It receives
usernameandpasswordarguments and returns whether they’re valid.
- Raises:
TypeError – If
credentialsorcheck_credentialsis wrong.ValueError – If
credentialsandcheck_credentialsare both provided or both not provided.