Server (threading) - websockets 11.0 documentation
Description: Creating a server: Running a server: Using a connection:

Hide navigation sidebar
Hide table of contents sidebar
Back to top
Toggle table of contents sidebar

# Server (`threading`)

## Creating a server

websockets.sync.server.serve(handler, host=None, port=None, *, sock=None, ssl_context=None, origins=None, extensions=None, subprotocols=None, select_subprotocol=None, process_request=None, process_response=None, server_header='Python/x.y.z websockets/X.Y', compression='deflate', open_timeout=10, close_timeout=10, max_size=2**20, logger=None, create_connection=None)

  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`.

  The handler receives a `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.

  `WebSocketServer` mirrors the API of `BaseServer`. Treat it as a context manager to ensure that it will be closed and call the `serve_forever()` method to serve requests:

      def handler(websocket):
          ...

      with websockets.sync.server.serve(handler, ...) as server:
          server.serve_forever()

  Parameters:

    - handler (Callable[[ServerConnection], 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.

    - sock (socket | None) – Preexisting TCP socket. `sock` replaces `host` and `port`. You may call `socket.create_server()` to create a suitable TCP socket.

    - ssl_context (SSLContext | None) – Configuration for enabling TLS on the connection.

    - origins (Sequence[Origin | None] | None) – Acceptable values of the `Origin` header, for defending against Cross-Site WebSocket Hijacking attacks. 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.

    - process_request (Callable[[ServerConnection, Request], 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_response (Callable[[ServerConnection, Request, Response], 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.

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

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

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

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

    - logger (Logger | LoggerAdapter | 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.

websockets.sync.server.unix_serve(handler, path=None, *, sock=None, ssl_context=None, origins=None, extensions=None, subprotocols=None, select_subprotocol=None, process_request=None, process_response=None, server_header='Python/x.y.z websockets/X.Y', compression='deflate', open_timeout=10, close_timeout=10, max_size=2**20, logger=None, create_connection=None)

  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:

    - handler (Callable[[ServerConnection], Any]) – Connection handler. It receives the WebSocket connection, which is a `ServerConnection`, in argument.

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

## Running a server

class websockets.sync.server.WebSocketServer(socket, handler, logger=None)

  WebSocket server returned by `serve()`.

  This class mirrors the API of `BaseServer`, notably the `serve_forever()` and `shutdown()` methods, as well as the context manager protocol.

  Parameters:

    - socket (socket.socket) – Server socket listening for new connections.

    - handler (Callable[[socket.socket, Any], None]) – Handler for one connection. Receives the socket and address returned by `accept()`.

    - logger (Optional[LoggerLike]) – Logger for this server.

  serve_forever()

    See `socketserver.BaseServer.serve_forever()`.

    This method doesn’t return. Calling `shutdown()` from another thread stops the server.

    Typical use:

        with serve(...) as server:
            server.serve_forever()

  shutdown()

    See `socketserver.BaseServer.shutdown()`.

  fileno()

    See `socketserver.BaseServer.fileno()`.

## Using a connection

class websockets.sync.server.ServerConnection(socket, protocol, *, close_timeout=10)

  Threaded implementation of a WebSocket server connection.

  `ServerConnection` provides `recv()` and `send()` methods for receiving and sending messages.

  It supports iteration to receive messages:

      for message in websocket:
          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.

  Parameters:

    - socket (socket.socket) – Socket connected to a WebSocket client.

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

    - close_timeout (Optional[float]) – Timeout for closing the connection in seconds.

  for ... in __iter__()

    Iterate on incoming messages.

    The iterator calls `recv()` and yields messages 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.

  recv(timeout=None)

    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.

    If `timeout` is `None`, block until a message is received. If `timeout` is set and no message is received within `timeout` seconds, raise `TimeoutError`. Set `timeout` to `0` to check if a message was already received.

    If the message is fragmented, wait until all fragments are received, reassemble them, and return the whole message.

    Returns:

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

    Raises:

      - ConnectionClosed – When the connection is closed.

      - RuntimeError – If two threads call `recv()` or `recv_streaming()` concurrently.

    Return type:

      str | bytes

  for ... in recv_streaming()

    Receive the next message frame by frame.

    If the message is fragmented, yield each fragment as it is received. The iterator must be fully consumed, or else the connection will become unusable.

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

    Returns:

      An iterator of strings (`str`) for a Text frame or bytestrings (`bytes`) for a Binary frame.

    Raises:

      - ConnectionClosed – When the connection is closed.

      - RuntimeError – If two threads call `recv()` or `recv_streaming()` concurrently.

    Return type:

      Iterator[str | bytes]

  send(message)

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

    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]) – Message to send.

    Raises:

      - ConnectionClosed – When the connection is closed.

      - RuntimeError – If a connection is busy sending a fragmented message.

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

  close(code=1000, reason='')

    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.

  ping(data=None)

    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:

      An event that will be set when the corresponding pong is received. You can ignore it if you don’t intend to wait.

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

    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:

      Event

  pong(data=b'')

    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.

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

  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.