Server (legacy asyncio
)¶
The legacy asyncio
implementation is deprecated.
The upgrade guide provides complete instructions to migrate your application.
Starting a server¶
- await websockets.legacy.server.serve(ws_handler, host=None, port=None, *, create_protocol=None, logger=None, compression='deflate', origins=None, extensions=None, subprotocols=None, extra_headers=None, server_header='Python/x.y.z websockets/X.Y', process_request=None, select_subprotocol=None, open_timeout=10, ping_interval=20, ping_timeout=20, close_timeout=10, max_size=2**20, max_queue=2**5, read_limit=2**16, write_limit=2**16, **kwds)[source]¶
Start a WebSocket server listening on
host
andport
.Whenever a client connects, the server creates a
WebSocketServerProtocol
, performs the opening handshake, and delegates to the connection handler,ws_handler
.The handler receives the
WebSocketServerProtocol
and uses it 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.
Awaiting
serve()
yields aWebSocketServer
. This object provides aclose()
method to shut down the server:# set this future to exit the server stop = asyncio.get_running_loop().create_future() server = await serve(...) await stop server.close() await server.wait_closed()
serve()
can be used as an asynchronous context manager. Then, the server is shut down automatically when exiting the context:# set this future to exit the server stop = asyncio.get_running_loop().create_future() async with serve(...): await stop
- Parameters:
ws_handler (Callable[[WebSocketServerProtocol], Awaitable[Any]] | Callable[[WebSocketServerProtocol, str], Awaitable[Any]]) – Connection handler. It receives the WebSocket connection, which is a
WebSocketServerProtocol
, in argument.host (str | Sequence[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.create_protocol (Callable[..., WebSocketServerProtocol] | None) – Factory for the
asyncio.Protocol
managing the connection. It defaults toWebSocketServerProtocol
. Set it to a wrapper or a subclass to customize connection handling.logger (LoggerLike | None) – Logger for this server. It defaults to
logging.getLogger("websockets.server")
. See the logging guide for details.compression (str | None) – The “permessage-deflate” extension is enabled by default. Set
compression
toNone
to disable it. See the compression guide for details.origins (Sequence[Origin | None] | None) – Acceptable values of the
Origin
header, for defending against Cross-Site WebSocket Hijacking attacks. IncludeNone
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.
extra_headers (HeadersLike | Callable[[str, Headers] | HeadersLike]) – Arbitrary HTTP headers to add to the response. This can be a
HeadersLike
or a callable taking the request path and headers in arguments and returning aHeadersLike
.server_header (str | None) – Value of the
Server
response header. It defaults to"Python/x.y.z websockets/X.Y"
. Setting it toNone
removes the header.process_request (Callable[[str, Headers], Awaitable[tuple[StatusLike, HeadersLike, bytes] | None]] | None) – Intercept HTTP request before the opening handshake. See
process_request()
for details.select_subprotocol (Callable[[Sequence[Subprotocol], Sequence[Subprotocol]], Subprotocol] | None) – Select a subprotocol supported by the client. See
select_subprotocol()
for details.open_timeout (float | None) – Timeout for opening connections in seconds.
None
disables the timeout.
See
WebSocketCommonProtocol
for the documentation ofping_interval
,ping_timeout
,close_timeout
,max_size
,max_queue
,read_limit
, andwrite_limit
.Any other keyword arguments are passed the event loop’s
create_server()
method.For example:
You can set
ssl
to aSSLContext
to enable TLS.You can set
sock
to asocket
that you created outside of websockets.
- Returns:
WebSocket server.
- Return type:
- await websockets.legacy.server.unix_serve(ws_handler, path=None, *, create_protocol=None, logger=None, compression='deflate', origins=None, extensions=None, subprotocols=None, extra_headers=None, server_header='Python/x.y.z websockets/X.Y', process_request=None, select_subprotocol=None, open_timeout=10, ping_interval=20, ping_timeout=20, close_timeout=10, max_size=2**20, max_queue=2**5, read_limit=2**16, write_limit=2**16, **kwds)[source]¶
Start a WebSocket server listening on a Unix socket.
This function is identical to
serve()
, except thehost
andport
arguments are replaced bypath
. It is only available on Unix.Unrecognized keyword arguments are passed the event loop’s
create_unix_server()
method.It’s useful for deploying a server behind a reverse proxy such as nginx.
Stopping a server¶
- class websockets.legacy.server.WebSocketServer(logger=None)[source]¶
WebSocket server returned by
serve()
.This class mirrors the API of
Server
.It keeps track of WebSocket connections in order to close them properly when shutting down.
- Parameters:
logger (LoggerLike | None) – Logger for this server. It defaults to
logging.getLogger("websockets.server")
. See the logging guide for details.
- close(close_connections=True)[source]¶
Close the server.
Close the underlying
Server
.When
close_connections
isTrue
, 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:
recv()
: when the connection is closed, it raisesConnectionClosedOK
;wait_closed()
: when the connection is closed, it returns.
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 cancelingserve_forever()
instead of exiting aserve()
context.
- sockets¶
Using a connection¶
- class websockets.legacy.server.WebSocketServerProtocol(ws_handler, ws_server, *, logger=None, origins=None, extensions=None, subprotocols=None, extra_headers=None, server_header='Python/x.y.z websockets/X.Y', process_request=None, select_subprotocol=None, open_timeout=10, ping_interval=20, ping_timeout=20, close_timeout=10, max_size=2**20, max_queue=2**5, read_limit=2**16, write_limit=2**16)[source]¶
WebSocket server connection.
WebSocketServerProtocol
providesrecv()
andsend()
coroutines 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.You may customize the opening handshake in a subclass by overriding
process_request()
orselect_subprotocol()
.- Parameters:
ws_server (WebSocketServer) – WebSocket server that created this connection.
See
serve()
for the documentation ofws_handler
,logger
,origins
,extensions
,subprotocols
,extra_headers
, andserver_header
.See
WebSocketCommonProtocol
for the documentation ofping_interval
,ping_timeout
,close_timeout
,max_size
,max_queue
,read_limit
, andwrite_limit
.- await recv()[source]¶
Receive the next message.
When the connection is closed,
recv()
raisesConnectionClosed
. Specifically, it raisesConnectionClosedOK
after a normal connection closure andConnectionClosedError
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 the next message. The next invocation ofrecv()
will return it.This makes it possible to enforce a timeout by wrapping
recv()
intimeout()
orwait_for()
.- Returns:
A string (
str
) for a Text frame. A bytestring (bytes
) for a Binary frame.- Raises:
ConnectionClosed – When the connection is closed.
RuntimeError – If two coroutines call
recv()
concurrently.
- Return type:
- await send(message)[source]¶
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.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 elsesend()
will raise aTypeError
and the connection will be closed.send()
rejects dict-like objects because this is often an error. (If you 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 withclose()
. Indeed, there are only two situations wheresend()
may yield control to the event loop and then get canceled; in both cases,close()
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.
close()
will likely time out then abort the TCP connection.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()
raisesConnectionClosed
. Specifically, it raisesConnectionClosedOK
after a normal connection closure andConnectionClosedError
after a protocol error or a network failure.- Parameters:
message (str | bytes | Iterable[str | bytes] | AsyncIterable[str | bytes]) – Message to send.
- Raises:
ConnectionClosed – When the connection is closed.
TypeError – If
message
doesn’t have a supported type.
- await close(code=CloseCode.NORMAL_CLOSURE, reason='')[source]¶
Perform the closing handshake.
close()
waits for the other end to complete the handshake and for the TCP connection to terminate. As a consequence, there’s no need to awaitwait_closed()
afterclose()
.close()
is idempotent: it doesn’t do anything once the connection is closed.Wrapping
close()
increate_task()
is safe, given that errors during connection termination aren’t particularly useful.Canceling
close()
is discouraged. If it takes too long, you can set a shorterclose_timeout
. If you don’t want to wait, let the Python process exit, then the OS will take care of closing the TCP connection.
- await wait_closed()[source]¶
Wait until the connection is closed.
This coroutine is identical to the
closed
attribute, except it can be awaited.This can make it easier to detect connection termination, regardless of its cause, in tasks that interact with the WebSocket connection.
- await ping(data=None)[source]¶
Send a Ping.
A ping may serve as a keepalive, as a check that the remote endpoint received all messages up to this point, or to measure
latency
.Canceling
ping()
is discouraged. Ifping()
doesn’t return immediately, it means the write buffer is full. If you don’t want to wait, you should close the connection.Canceling the
Future
returned byping()
has no effect.- Parameters:
data (str | bytes | None) – Payload of the ping. A string will be encoded to UTF-8. If
data
isNone
, 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.
RuntimeError – If another ping was sent with the same data and the corresponding pong wasn’t received yet.
- Return type:
- await pong(data=b'')[source]¶
Send a Pong.
An unsolicited pong may serve as a unidirectional heartbeat.
Canceling
pong()
is discouraged. Ifpong()
doesn’t return immediately, it means the write buffer is full. If you don’t want to wait, you should close the connection.- Parameters:
data (str | bytes) – Payload of the pong. A string will be encoded to UTF-8.
- Raises:
ConnectionClosed – When the connection is closed.
You can customize the opening handshake in a subclass by overriding these methods:
- await process_request(path, request_headers)[source]¶
Intercept the HTTP request and return an HTTP response if appropriate.
You may override this method in a
WebSocketServerProtocol
subclass, for example:to return an HTTP 200 OK response on a given path; then a load balancer can use this path for a health check;
to authenticate the request and return an HTTP 401 Unauthorized or an HTTP 403 Forbidden when authentication fails.
You may also override this method with the
process_request
argument ofserve()
andWebSocketServerProtocol
. This is equivalent, exceptprocess_request
won’t have access to the protocol instance, so it can’t store information for later use.process_request()
is expected to complete quickly. If it may run for a long time, then it should awaitwait_closed()
and exit ifwait_closed()
completes, or else it could prevent the server from shutting down.- Parameters:
- Returns:
None
to continue the WebSocket handshake normally.An HTTP response, represented by a 3-uple of the response status, headers, and body, to abort the WebSocket handshake and return that HTTP response instead.
- Return type:
tuple[StatusLike, HeadersLike, bytes] | None
- select_subprotocol(client_subprotocols, server_subprotocols)[source]¶
Pick a subprotocol among those supported by the client and the server.
If several subprotocols are available, select the preferred subprotocol by giving equal weight to the preferences of the client and the server.
If no subprotocol is available, proceed without a subprotocol.
You may provide a
select_subprotocol
argument toserve()
orWebSocketServerProtocol
to override this logic. For example, you could reject the handshake if the client doesn’t support a particular subprotocol, rather than accept the handshake without that subprotocol.- Parameters:
client_subprotocols (Sequence[Subprotocol]) – List of subprotocols offered by the client.
server_subprotocols (Sequence[Subprotocol]) – List of subprotocols available on the server.
- Returns:
Selected subprotocol, if a common subprotocol was found.
None
to continue without a subprotocol.- Return type:
WebSocket connection objects also provide these attributes:
- 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()
.None
if the TCP connection isn’t established yet.
- 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()
.None
if the TCP connection isn’t established yet.
- property open: bool¶
True
when the connection is open;False
otherwise.This attribute may be used to detect disconnections. However, this approach is discouraged per the EAFP principle. Instead, you should handle
ConnectionClosed
exceptions.
- property closed: bool¶
True
when the connection is closed;False
otherwise.Be aware that both
open
andclosed
areFalse
during the opening and closing sequences.
- 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
is0
.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()
.
The following attributes are available after the opening handshake, once the WebSocket connection is open:
- subprotocol: Subprotocol | None¶
Subprotocol, if one was negotiated.
The following attributes are available after the closing handshake, once the WebSocket connection is closed:
- property close_code: int | None¶
WebSocket close code, defined in section 7.1.5 of RFC 6455.
None
if the connection isn’t closed yet.
- property close_reason: str | None¶
WebSocket close reason, defined in section 7.1.6 of RFC 6455.
None
if the connection isn’t closed yet.
Broadcast¶
- websockets.legacy.server.broadcast(websockets, 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
, ormemoryview
) 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
andping_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, 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. On Python 3.11 and above, you may setraise_exceptions
toTrue
to 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.
Basic authentication¶
websockets supports HTTP Basic Authentication according to RFC 7235 and RFC 7617.
- websockets.legacy.auth.basic_auth_protocol_factory(realm=None, credentials=None, check_credentials=None, create_protocol=None)[source]¶
Protocol factory that enforces HTTP Basic Auth.
basic_auth_protocol_factory()
is designed to integrate withserve()
like this:serve( ..., create_protocol=basic_auth_protocol_factory( realm="my dev server", credentials=("hello", "iloveyou"), ) )
- Parameters:
realm (str | None) – 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]] | None) – Coroutine that verifies credentials. It receives
username
andpassword
arguments and returns abool
. One ofcredentials
orcheck_credentials
must be provided but not both.create_protocol (Callable[[...], BasicAuthWebSocketServerProtocol] | None) – Factory that creates the protocol. By default, this is
BasicAuthWebSocketServerProtocol
. It can be replaced by a subclass.
- Raises:
TypeError – If the
credentials
orcheck_credentials
argument is wrong.
- class websockets.legacy.auth.BasicAuthWebSocketServerProtocol(*args, realm=None, check_credentials=None, **kwargs)[source]¶
WebSocket server protocol that enforces HTTP Basic Auth.
- realm: str = ''¶
Scope of protection.
If provided, it should contain only ASCII characters because the encoding of non-ASCII characters is undefined.