Server#

asyncio#

Starting a server#

await websockets.server.serve(ws_handler, host=None, port=None, *, create_protocol=None, logger=None, compression='deflate', origins=None, extensions=None, subprotocols=None, extra_headers=None, process_request=None, select_subprotocol=None, 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 and port.

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 a WebSocketServer. This object provides close() and wait_closed() methods for shutting down the server.

serve() can be used as an asynchronous context manager:

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

async with serve(...):
    await stop

The server is shut down automatically when exiting the context.

Parameters
  • ws_handler (Union[Callable[[WebSocketServerProtocol], Awaitable[Any]], Callable[[WebSocketServerProtocol, str], Awaitable[Any]]]) – connection handler. It receives the WebSocket connection, which is a WebSocketServerProtocol, in argument.

  • host (Optional[Union[str, Sequence[str]]]) – network interfaces the server is bound to; see create_server() for details.

  • port (Optional[int]) – TCP port the server listens on; see create_server() for details.

  • create_protocol (Optional[Callable[[Any], WebSocketServerProtocol]]) – factory for the asyncio.Protocol managing the connection; defaults to WebSocketServerProtocol; may be set to a wrapper or a subclass to customize connection handling.

  • logger (Optional[LoggerLike]) – logger for this server; defaults to logging.getLogger("websockets.server"); see the logging guide for details.

  • compression (Optional[str]) – shortcut that enables the “permessage-deflate” extension by default; may be set to None to disable compression; see the compression guide for details.

  • origins (Optional[Sequence[Optional[Origin]]]) – acceptable values of the Origin header; include None in the list if the lack of an origin is acceptable. This is useful for defending against Cross-Site WebSocket Hijacking attacks.

  • extensions (Optional[Sequence[ServerExtensionFactory]]) – list of supported extensions, in order in which they should be tried.

  • subprotocols (Optional[Sequence[Subprotocol]]) – list of supported subprotocols, in order of decreasing preference.

  • extra_headers (Union[HeadersLike, Callable[[str, Headers], HeadersLike]]) – arbitrary HTTP headers to add to the request; this can be a HeadersLike or a callable taking the request path and headers in arguments and returning a HeadersLike.

  • process_request (Optional[Callable[[str, Headers], Awaitable[Optional[Tuple[http.HTTPStatus, HeadersLike, bytes]]]]]) – intercept HTTP request before the opening handshake; see process_request() for details.

  • select_subprotocol (Optional[Callable[[Sequence[Subprotocol], Sequence[Subprotocol]], Subprotocol]]) – select a subprotocol supported by the client; see select_subprotocol() for details.

See WebSocketCommonProtocol for the documentation of ping_interval, ping_timeout, close_timeout, max_size, max_queue, read_limit, and write_limit.

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

For example:

  • You can set ssl to a SSLContext to enable TLS.

  • You can set sock to a socket that you created outside of websockets.

Returns

WebSocket server.

Return type

WebSocketServer

await websockets.server.unix_serve(ws_handler, path=None, *, create_protocol=None, logger=None, compression='deflate', origins=None, extensions=None, subprotocols=None, extra_headers=None, process_request=None, select_subprotocol=None, 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]#

Similar to serve(), but for listening on Unix sockets.

This function builds upon the event loop’s create_unix_server() method.

It is only available on Unix.

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

Parameters

path (Optional[str]) – file system path to the Unix socket.

Stopping a server#

class websockets.server.WebSocketServer(logger=None)[source]#

WebSocket server returned by serve().

This class provides the same interface as Server, notably the close() and wait_closed() methods.

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

Parameters

logger (Optional[LoggerLike]) – logger for this server; defaults to logging.getLogger("websockets.server"); see the logging guide for details.

close()[source]#

Close the server.

This method:

  • closes the underlying Server;

  • rejects new WebSocket connections with an HTTP 503 (service unavailable) error; this happens when the server accepted the TCP connection but didn’t complete the WebSocket opening handshake prior to closing;

  • closes open WebSocket connections with close code 1001 (going away).

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

await serve_forever()[source]#

See asyncio.Server.serve_forever().

sockets#

See asyncio.Server.sockets.

Using a connection#

class websockets.server.WebSocketServerProtocol(ws_handler, ws_server, *, logger=None, origins=None, extensions=None, subprotocols=None, extra_headers=None, process_request=None, select_subprotocol=None, 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 provides recv() and send() 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). 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() or select_subprotocol().

Parameters

ws_server (WebSocketServer) – WebSocket server that created this connection.

See serve() for the documentation of ws_handler, logger, origins, extensions, subprotocols, and extra_headers.

See WebSocketCommonProtocol for the documentation of ping_interval, ping_timeout, close_timeout, max_size, max_queue, read_limit, and write_limit.

await recv()[source]#

Receive the next message.

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

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

Returns

A string (str) for a Text frame. A bytestring (bytes) for a Binary frame.

Return type

Data

Raises
await send(message)[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.

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 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 (Union[Data, Iterable[Data], AsyncIterable[Data]) – 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. As a consequence, there’s no need to await wait_closed() after close().

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

Wrapping close() in create_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 shorter close_timeout. If you don’t want to wait, let the Python process exit, then the OS will take care of closing the TCP connection.

Parameters
  • code (int) – WebSocket close code.

  • reason (str) – WebSocket close reason.

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 or as a check that the remote endpoint received all messages up to this point

Canceling ping() is discouraged. If ping() 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 by ping() has no effect.

Parameters

data (Optional[Data]) – payload of the ping; a string will be encoded to UTF-8; or None to generate a payload containing 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.

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

Return type

Future

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.

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

Send a Pong.

An unsolicited pong may serve as a unidirectional heartbeat.

Canceling pong() is discouraged. If pong() 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 (Data) – 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 a 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 a HTTP 401 Unauthorized or a HTTP 403 Forbidden when authentication fails.

You may also override this method with the process_request argument of serve() and WebSocketServerProtocol. This is equivalent, except process_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 await wait_closed() and exit if wait_closed() completes, or else it could prevent the server from shutting down.

Parameters
  • path (str) – request path, including optional query string.

  • request_headers (Headers) – request headers.

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

Optional[Tuple[http.HTTPStatus, HeadersLike, bytes]]

select_subprotocol(client_subprotocols, server_subprotocols)[source]#

Pick a subprotocol among those offered by the client.

If several subprotocols are supported by the client and the server, the default implementation selects the preferred subprotocol by giving equal value to the priorities of the client and the server. If no subprotocol is supported by the client and the server, it proceeds without a subprotocol.

This is unlikely to be the most useful implementation in practice. Many servers providing a subprotocol will require that the client uses that subprotocol. Such rules can be implemented in a subclass.

You may also override this method with the select_subprotocol argument of serve() and WebSocketServerProtocol.

Parameters
Returns

Selected subprotocol.

None to continue without a subprotocol.

Return type

Optional[Subprotocol]

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

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 and closed are False during the opening and closing sequences.

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

path: str#

Path of the opening handshake request.

request_headers: Headers#

Opening handshake request headers.

response_headers: Headers#

Opening handshake response headers.

subprotocol: Optional[Subprotocol]#

Subprotocol, if one was negotiated.

The following attributes are available after the closing handshake, once the WebSocket connection is closed:

property close_code: Optional[int]#

WebSocket close code, defined in section 7.1.5 of RFC 6455.

None if the connection isn’t closed yet.

property close_reason: Optional[str]#

WebSocket close reason, defined in section 7.1.6 of RFC 6455.

None if the connection isn’t closed yet.

Basic authentication#

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

websockets.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 with serve() like this:

websockets.serve(
    ...,
    create_protocol=websockets.basic_auth_protocol_factory(
        realm="my dev server",
        credentials=("hello", "iloveyou"),
    )
)
Parameters
Raises

TypeError – if the credentials or check_credentials argument is wrong.

class websockets.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.

username: Optional[str] = None#

Username of the authenticated user.

await check_credentials(username, password)[source]#

Check whether credentials are authorized.

This coroutine may be overridden in a subclass, for example to authenticate against a database or an external service.

Parameters
  • username (str) – HTTP Basic Auth username.

  • password (str) – HTTP Basic Auth password.

Returns

True if the handshake should continue; False if it should fail with a HTTP 401 error.

Return type

bool

Sans-I/O#

class websockets.server.ServerConnection(origins=None, extensions=None, subprotocols=None, state=State.CONNECTING, max_size=2**20, logger=None)[source]#

Sans-I/O implementation of a WebSocket server connection.

Parameters
  • origins (Optional[Sequence[Optional[Origin]]]) – acceptable values of the Origin header; include None in the list if the lack of an origin is acceptable. This is useful for defending against Cross-Site WebSocket Hijacking attacks.

  • extensions (List[Extension]) – list of supported extensions, in order in which they should be tried.

  • subprotocols (Optional[Sequence[Subprotocol]]) – list of supported subprotocols, in order of decreasing preference.

  • state (State) – initial state of the WebSocket connection.

  • max_size (Optional[int]) – maximum size of incoming messages in bytes; None to disable the limit.

  • logger (Union[Logger, LoggerAdapter]) – logger for this connection; defaults to logging.getLogger("websockets.client"); see the logging guide for details.

receive_data(data)[source]#

Receive data from the network.

After calling this method:

Raises

EOFError – if receive_eof() was called earlier.

receive_eof()[source]#

Receive the end of the data stream from the network.

After calling this method:

Raises

EOFError – if receive_eof() was called earlier.

accept(request)[source]#

Create a handshake response to accept the connection.

If the connection cannot be established, the handshake response actually rejects the handshake.

You must send the handshake response with send_response().

You can modify it before sending it, for example to add HTTP headers.

Parameters

request (Request) – WebSocket handshake request event received from the client.

Returns

WebSocket handshake response event to send to the client.

Return type

Response

reject(status, text)[source]#

Create a handshake response to reject the connection.

A short plain text response is the best fallback when failing to establish a WebSocket connection.

You must send the handshake response with send_response().

You can modify it before sending it, for example to alter HTTP headers.

Parameters
  • status (HTTPStatus) – HTTP status code.

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

Returns

WebSocket handshake response event to send to the client.

Return type

Response

send_response(response)[source]#

Send a handshake response to the client.

Parameters

response (Response) – WebSocket handshake response event to send.

send_continuation(data, fin)[source]#

Send a Continuation frame.

Parameters
  • data (bytes) – payload containing the same kind of data as the initial frame.

  • fin (bool) – FIN bit; set it to True if this is the last frame of a fragmented message and to False otherwise.

Raises

ProtocolError – if a fragmented message isn’t in progress.

send_text(data, fin=True)[source]#

Send a Text frame.

Parameters
  • data (bytes) – payload containing text encoded with UTF-8.

  • fin (bool) – FIN bit; set it to False if this is the first frame of a fragmented message.

Raises

ProtocolError – if a fragmented message is in progress.

send_binary(data, fin=True)[source]#

Send a Binary frame.

Parameters
  • data (bytes) – payload containing arbitrary binary data.

  • fin (bool) – FIN bit; set it to False if this is the first frame of a fragmented message.

Raises

ProtocolError – if a fragmented message is in progress.

send_close(code=None, reason='')[source]#

Send a Close frame.

Parameters
Raises

ProtocolError – if a fragmented message is being sent, if the code isn’t valid, or if a reason is provided without a code

send_ping(data)[source]#

Send a Ping frame.

Parameters

data (bytes) – payload containing arbitrary binary data.

send_pong(data)[source]#

Send a Pong frame.

Parameters

data (bytes) – payload containing arbitrary binary data.

fail(code, reason='')[source]#

Fail the WebSocket connection.

Parameters
  • code (int) – close code

  • reason (str) – close reason

Raises

ProtocolError – if the code isn’t valid.

events_received()[source]#

Fetch events generated from data received from the network.

Call this method immediately after any of the receive_*() methods.

Process resulting events, likely by passing them to the application.

Returns

Events read from the connection.

Return type

List[Event]

data_to_send()[source]#

Obtain data to send to the network.

Call this method immediately after any of the receive_*(), send_*(), or fail() methods.

Write resulting data to the connection.

The empty bytestring SEND_EOF signals the end of the data stream. When you receive it, half-close the TCP connection.

Returns

Data to write to the connection.

Return type

List[bytes]

close_expected()[source]#

Tell if the TCP connection is expected to close soon.

Call this method immediately after any of the receive_*() or fail() methods.

If it returns True, schedule closing the TCP connection after a short timeout if the other side hasn’t already closed it.

Returns

Whether the TCP connection is expected to close soon.

Return type

bool

id: uuid.UUID#

Unique identifier of the connection. Useful in logs.

logger: LoggerLike#

Logger for this connection.

property state: State#

WebSocket connection state.

Defined in 4.1, 4.2, 7.1.3, and 7.1.4 of RFC 6455.

property close_code: Optional[int]#

WebSocket close code.

None if the connection isn’t closed yet.

property close_reason: Optional[str]#

WebSocket close reason.

None if the connection isn’t closed yet.

property close_exc: ConnectionClosed#

Exception to raise when trying to interact with a closed connection.

Don’t raise this exception while the connection state is CLOSING; wait until it’s CLOSED.

Indeed, the exception includes the close code and reason, which are known only once the connection is closed.

Raises

AssertionError – if the connection isn’t closed yet.