Server (asyncio)

Creating a server

await websockets.asyncio.server.serve(handler, host=None, port=None, *, origins=None, extensions=None, subprotocols=None, select_subprotocol=None, compression='deflate', process_request=None, process_response=None, server_header='Python/3.10 websockets/15.1.dev2+gbb78c20', open_timeout=10, ping_interval=20, ping_timeout=20, close_timeout=10, max_size=1048576, max_queue=16, write_limit=32768, logger=None, create_connection=None, **kwargs)[source]

Create a WebSocket server listening on host and port.

Whenever a client connects, the server creates a ServerConnection, performs the opening handshake, and delegates to the handler coroutine.

The handler receives the ServerConnection instance, 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.

This coroutine returns a Server whose API mirrors asyncio.Server. Treat it as an asynchronous context manager to ensure that the server will be closed:

from websockets.asyncio.server import serve

def handler(websocket):
    ...

# set this future to exit the server
stop = asyncio.get_running_loop().create_future()

async with serve(handler, host, port):
    await stop

Alternatively, call serve_forever() to serve requests and cancel it to stop the server:

server = await serve(handler, host, port)
await server.serve_forever()
Parameters:
  • handler (Callable[[ServerConnection], Awaitable[None]]) – Connection handler. It receives the WebSocket connection, which is a ServerConnection, in argument.

  • host (str | None) – Network interfaces the server binds to. See create_server() for details.

  • port (int | None) – TCP port the server listens on. See create_server() for details.

  • origins (Sequence[Origin | re.Pattern[str] | None] | None) – Acceptable values of the Origin header, for defending against Cross-Site WebSocket Hijacking attacks. Values can be str to test for an exact match or regular expressions compiled by re.compile() to test against a pattern. Include None in the list if the lack of an origin is acceptable.

  • extensions (Sequence[ServerExtensionFactory] | None) – List of supported extensions, in order in which they should be negotiated and run.

  • subprotocols (Sequence[Subprotocol] | None) – List of supported subprotocols, in order of decreasing preference.

  • select_subprotocol (Callable[[ServerConnection, Sequence[Subprotocol]], Subprotocol | None] | None) – Callback for selecting a subprotocol among those supported by the client and the server. It receives a ServerConnection (not a ServerProtocol!) instance and a list of subprotocols offered by the client. Other than the first argument, it has the same behavior as the ServerProtocol.select_subprotocol method.

  • compression (str | None) – The “permessage-deflate” extension is enabled by default. Set compression to None to disable it. See the compression guide for details.

  • process_request (Callable[[ServerConnection, Request], Awaitable[Response | None] | Response | None] | None) – Intercept the request during the opening handshake. Return an HTTP response to force the response or None to continue normally. When you force an HTTP 101 Continue response, the handshake is successful. Else, the connection is aborted. process_request may be a function or a coroutine.

  • process_response (Callable[[ServerConnection, Request, Response], Awaitable[Response | None] | Response | None] | None) – Intercept the response during the opening handshake. Return an HTTP response to force the response or None to continue normally. When you force an HTTP 101 Continue response, the handshake is successful. Else, the connection is aborted. process_response may be a function or a coroutine.

  • server_header (str | None) – Value of the Server response header. It defaults to "Python/x.y.z websockets/X.Y". Setting it to None removes the header.

  • open_timeout (float | None) – Timeout for opening connections in seconds. None disables the timeout.

  • ping_interval (float | None) – Interval between keepalive pings in seconds. None disables keepalive.

  • ping_timeout (float | None) – Timeout for keepalive pings in seconds. None disables timeouts.

  • close_timeout (float | None) – Timeout for closing connections in seconds. None disables the timeout.

  • max_size (int | None) – Maximum size of incoming messages in bytes. None disables the limit.

  • max_queue (int | None | tuple[int | None, int | None]) – 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 to None, although that’s a bad idea.

  • write_limit (int | tuple[int, int | None]) – High-water mark of write buffer in bytes. It is passed to set_write_buffer_limits(). It defaults to 32 KiB. You may pass a (high, low) tuple to set the high-water and low-water marks.

  • logger (LoggerLike | None) – Logger for this server. It defaults to logging.getLogger("websockets.server"). See the logging guide for details.

  • create_connection (type[ServerConnection] | None) – Factory for the ServerConnection managing the connection. Set it to a wrapper or a subclass to customize connection handling.

Any other keyword arguments are passed to the event loop’s create_server() method.

For example:

await websockets.asyncio.server.unix_serve(handler, path=None, **kwargs)[source]

Create a WebSocket server listening on a Unix socket.

This function is identical to serve(), except the host and port arguments are replaced by path. It’s only available on Unix.

It’s useful for deploying a server behind a reverse proxy such as nginx.

Parameters:

Routing connections

await websockets.asyncio.router.route(url_map, *args, server_name=None, ssl=None, create_router=None, **kwargs)[source]

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 as serve(), except as described below.

The first argument is a werkzeug.routing.Map that 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.asyncio.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 future to exit the server
stop = asyncio.get_running_loop().create_future()

async with route(url_map, ...) as server:
    await stop

Refer to the documentation of werkzeug.routing for details.

If you define redirects with Rule(..., redirect_to=...) in the URL map, when the server runs behind a reverse proxy that modifies the Host header or terminates TLS, you need additional configuration:

  • Set server_name to the name of the server as seen by clients. When not provided, websockets uses the value of the Host header.

  • Set ssl=True to generate wss:// URIs without actually enabling TLS. Under the hood, this bind the URL map with a url_scheme of wss:// instead of ws://.

There is no need to specify websocket=True in each rule. It is added automatically.

Parameters:
  • url_map (Map) – Mapping of URL patterns to connection handlers.

  • server_name (str | None) – Name of the server as seen by clients. If None, websockets uses the value of the Host header.

  • ssl (SSLContext | Literal[True] | None) – Configuration for enabling TLS on the connection. Set it to True if a reverse proxy terminates TLS connections.

  • create_router (type[Router] | None) – Factory for the Router dispatching requests to handlers. Set it to a wrapper or a subclass to customize routing.

await websockets.asyncio.router.unix_route(url_map, path=None, **kwargs)[source]

Create a WebSocket Unix server dispatching connections to different handlers.

unix_route() combines the behaviors of route() and unix_serve().

Parameters:
  • url_map (Map) – Mapping of URL patterns to connection handlers.

  • path (str | None) – File system path to the Unix socket.

class websockets.asyncio.router.Router(url_map, server_name=None, url_scheme='ws')[source]

WebSocket router supporting route().

Running a server

class websockets.asyncio.server.Server(handler, *, process_request=None, process_response=None, server_header='Python/3.10 websockets/15.1.dev2+gbb78c20', open_timeout=10, logger=None)[source]

WebSocket server returned by serve().

This class mirrors the API of asyncio.Server.

It keeps track of WebSocket connections in order to close them properly when shutting down.

Parameters:
  • handler (Callable[[ServerConnection], Awaitable[None]]) – Connection handler. It receives the WebSocket connection, which is a ServerConnection, in argument.

  • process_request (Callable[[ServerConnection, Request], Awaitable[Response | None] | Response | None] | None) – Intercept the request during the opening handshake. Return an HTTP response to force the response. Return None to continue normally. When you force an HTTP 101 Continue response, the handshake is successful. Else, the connection is aborted. process_request may be a function or a coroutine.

  • process_response (Callable[[ServerConnection, Request, Response], Awaitable[Response | None] | Response | None] | None) – Intercept the response during the opening handshake. Modify the response or return a new HTTP response to force the response. Return None to continue normally. When you force an HTTP 101 Continue response, the handshake is successful. Else, the connection is aborted. process_response may be a function or a coroutine.

  • server_header (str | None) – Value of the Server response header. It defaults to "Python/x.y.z websockets/X.Y". Setting it to None removes the header.

  • open_timeout (float | None) – Timeout for opening connections in seconds. None disables the timeout.

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

close(close_connections=True)[source]

Close the server.

  • Close the underlying asyncio.Server.

  • When close_connections is True, 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).

  • Wait until all connection handlers terminate.

close() is idempotent.

await wait_closed()[source]

Wait until the server is closed.

When wait_closed() returns, all TCP connections are closed and all connection handlers have returned.

To ensure a fast shutdown, a connection handler should always be awaiting at least one of:

Then the connection handler is immediately notified of the shutdown; it can clean up and exit.

get_loop()[source]

See asyncio.Server.get_loop().

is_serving()[source]

See asyncio.Server.is_serving().

await start_serving()[source]

See asyncio.Server.start_serving().

Typical use:

server = await serve(..., start_serving=False)
# perform additional setup here...
# ... then start the server
await server.start_serving()
await serve_forever()[source]

See asyncio.Server.serve_forever().

Typical use:

server = await serve(...)
# this coroutine doesn't return
# canceling it stops the server
await server.serve_forever()

This is an alternative to using serve() as an asynchronous context manager. Shutdown is triggered by canceling serve_forever() instead of exiting a serve() context.

sockets

See asyncio.Server.sockets.

Using a connection

class websockets.asyncio.server.ServerConnection(protocol, server, *, ping_interval=20, ping_timeout=20, close_timeout=10, max_queue=16, write_limit=32768)[source]

asyncio implementation of a WebSocket server connection.

ServerConnection provides recv() and send() 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 ConnectionClosedError when the connection is closed with any other code.

The ping_interval, ping_timeout, close_timeout, max_queue, and write_limit arguments have the same meaning as in serve().

Parameters:
  • protocol (ServerProtocol) – Sans-I/O connection.

  • server (Server) – Server that manages this connection.

async for ... in __aiter__()[source]

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 ConnectionClosedError exception after a protocol error or a network failure.

await recv(decode=None)[source]

Receive the next message.

When the connection is closed, recv() raises ConnectionClosed. Specifically, it raises ConnectionClosedOK after a normal closure and ConnectionClosedError after 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 of recv() will return the next message.

This makes it possible to enforce a timeout by wrapping recv() in timeout() or wait_for().

When the message is fragmented, recv() waits until all fragments are received, reassembles them, and returns the whole message.

Parameters:

decode (bool | None) – Set this flag to override the default behavior of returning str or bytes. 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 decode argument:

  • Set decode=False to 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=True to 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:
Return type:

str | bytes

async for ... in recv_streaming(decode=None)[source]

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() or recv_streaming() will raise ConcurrencyError, making the connection unusable.

recv_streaming() raises the same exceptions as recv().

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 with close().

Parameters:

decode (bool | None) – Set this flag to override the default behavior of returning str or bytes. 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 decode argument:

  • Set decode=False to 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=True to 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:
Return type:

AsyncIterator[str | bytes]

await send(message, text=None)[source]

Send a message.

A string (str) is sent as a Text frame. A bytestring or bytes-like object (bytes, bytearray, or memoryview) is sent as a Binary frame.

You may override this behavior with the text argument:

  • Set text=True to send a bytestring or bytes-like object (bytes, bytearray, or memoryview) as 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=False to 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 an 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 else send() will raise a TypeError and 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 its keys() method and pass the result to send().)

Canceling send() is discouraged. Instead, you should close the connection with close(). Indeed, there are only two situations where send() may yield control to the event loop and then get canceled; in both cases, close() has the same effect and is more clear:

  1. 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. close() will likely time out then abort the TCP connection.

  2. message is 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() raises ConnectionClosed. Specifically, it raises ConnectionClosedOK after a normal connection closure and ConnectionClosedError after a protocol error or a network failure.

Parameters:

message (str | bytes | Iterable[str | bytes] | AsyncIterable[str | bytes]) – Message to send.

Raises:
await close(code=1000, reason='')[source]

Perform the closing handshake.

close() waits for the other end to complete the handshake and for the TCP connection to terminate.

close() is idempotent: it doesn’t do anything once the connection is closed.

Parameters:
  • code (int) – WebSocket close code.

  • reason (str) – WebSocket close reason.

await wait_closed()[source]

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)[source]

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 (str | bytes | None) – Payload of the ping. A str will be encoded to UTF-8. If data is None, the payload is four random bytes.

Returns:

A future that will be completed when the corresponding pong is received. You can ignore it if you don’t intend to wait. The result of the future is the latency of the connection in seconds.

pong_waiter = await ws.ping()
# only if you want to wait for the corresponding pong
latency = await pong_waiter

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.

Return type:

Awaitable[float]

await pong(data=b'')[source]

Send a Pong.

An unsolicited pong may serve as a unidirectional heartbeat.

Parameters:

data (str | bytes) – Payload of the pong. A str will be encoded to UTF-8.

Raises:

ConnectionClosed – When the connection is closed.

respond(status, text)[source]

Create a plain text HTTP response.

process_request and process_response may 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 (HTTPStatus | int) – HTTP status code.

  • text (str) – HTTP response body; it will be encoded to UTF-8.

Returns:

HTTP response to send to the client.

Return type:

Response

WebSocket connection objects also provide these attributes:

id: uuid.UUID

Unique identifier of the connection. Useful in logs.

logger: LoggerLike

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, latency is 0.

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() or send() and handle ConnectionClosed exceptions.

The following attributes are available after the opening handshake, once the WebSocket connection is open:

request: Request | None

Opening handshake request.

response: Response | None

Opening handshake response.

property subprotocol: Subprotocol | None

Subprotocol negotiated during the opening handshake.

None if 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 ConnectionClosed exceptions.

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 ConnectionClosed exceptions.

Broadcast

websockets.asyncio.server.broadcast(connections, message, raise_exceptions=False)[source]

Broadcast a message to several WebSocket connections.

A string (str) is sent as a Text frame. A bytestring or bytes-like object (bytes, bytearray, or memoryview) is sent as a Binary frame.

broadcast() pushes the message synchronously to all connections even if their write buffers are overflowing. There’s no backpressure.

If you broadcast messages faster than a connection can handle them, messages will pile up in its write buffer until the connection times out. Keep ping_interval and ping_timeout low to prevent excessive memory usage from slow connections.

Unlike send(), broadcast() doesn’t support sending fragmented messages. Indeed, fragmentation is useful for sending large messages without buffering them in memory, while broadcast() 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. On Python 3.11 and above, you may set raise_exceptions to True to record failures and raise all exceptions in a PEP 654 ExceptionGroup.

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.

Parameters:
  • websockets – WebSocket connections to which the message will be sent.

  • message (str | bytes) – Message to send.

  • raise_exceptions (bool) – Whether to raise an exception in case of failures.

Raises:

TypeError – If message doesn’t have a supported type.

HTTP Basic Authentication

websockets supports HTTP Basic Authentication according to RFC 7235 and RFC 7617.

websockets.asyncio.server.basic_auth(realm='', credentials=None, check_credentials=None)[source]

Factory for process_request to enforce HTTP Basic Authentication.

basic_auth() is designed to integrate with serve() 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 username attribute is set. If it fails, the server responds with an HTTP 401 Unauthorized status.

One of credentials or check_credentials must be provided; not both.

Parameters:
  • realm (str) – 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 (tuple[str, str] | Iterable[tuple[str, str]] | None) – Hard coded authorized credentials. It can be a (username, password) pair or a list of such pairs.

  • check_credentials (Callable[[str, str], Awaitable[bool] | bool] | None) – Function or coroutine that verifies credentials. It receives username and password arguments and returns whether they’re valid.

Raises:
  • TypeError – If credentials or check_credentials is wrong.

  • ValueError – If credentials and check_credentials are both provided or both not provided.