Server (threading
)¶
Creating a server¶
- websockets.sync.server.serve(handler, host=None, port=None, *, sock=None, ssl=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, logger=None, create_connection=None, **kwargs)[source]¶
Create a WebSocket server listening on
host
andport
.Whenever a client connects, the server creates a
ServerConnection
, performs the opening handshake, and delegates to thehandler
.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 function returns a
Server
whose API mirrorsBaseServer
. Treat it as a context manager to ensure that it will be closed and callserve_forever()
to serve requests:from websockets.sync.server import serve def handler(websocket): ... with 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
replaceshost
andport
. You may callsocket.create_server()
to create a suitable TCP socket.ssl (SSLContext | None) – Configuration for enabling TLS on the connection.
origins (Sequence[Origin | Pattern[str] | None] | None) – Acceptable values of the
Origin
header, for defending against Cross-Site WebSocket Hijacking attacks. Values can bestr
to test for an exact match or regular expressions compiled byre.compile()
to test against a pattern. 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.
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 aServerProtocol
!) instance and a list of subprotocols offered by the client. Other than the first argument, it has the same behavior as theServerProtocol.select_subprotocol
method.compression (str | None) – The “permessage-deflate” extension is enabled by default. Set
compression
toNone
to disable it. See the compression guide for details.process_request (Callable[[ServerConnection, Request], 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_response (Callable[[ServerConnection, Request, Response], 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.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.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 toNone
, although that’s a bad idea.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.
Any other keyword arguments are passed to
create_server()
.
- websockets.sync.server.unix_serve(handler, path=None, **kwargs)[source]¶
Create a WebSocket server listening on a Unix socket.
This function accepts the same keyword arguments as
serve()
.It’s only available on Unix.
It’s useful for deploying a server behind a reverse proxy such as nginx.
- Parameters:
handler (Callable[[ServerConnection], None]) – Connection handler. It receives the WebSocket connection, which is a
ServerConnection
, in argument.
Routing connections¶
- websockets.sync.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 asserve()
, 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.sync.router import route from werkzeug.routing import Map, Rule def channel_handler(websocket, channel_id): ... url_map = Map([ Rule("/channel/<uuid:channel_id>", endpoint=channel_handler), ... ]) with route(url_map, ...) as server: server.serve_forever()
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 theHost
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 theHost
header.Set
ssl=True
to generatewss://
URIs without actually enabling TLS. Under the hood, this bind the URL map with aurl_scheme
ofwss://
instead ofws://
.
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 theHost
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.
- websockets.sync.router.unix_route(url_map, path=None, **kwargs)[source]¶
Create a WebSocket Unix server dispatching connections to different handlers.
unix_route()
combines the behaviors ofroute()
andunix_serve()
.
Running a server¶
- class websockets.sync.server.Server(socket, handler, logger=None)[source]¶
WebSocket server returned by
serve()
.This class mirrors the API of
BaseServer
, notably theserve_forever()
andshutdown()
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 (LoggerLike | None) – Logger for this server. It defaults to
logging.getLogger("websockets.server")
. See the logging guide for details.
- serve_forever()[source]¶
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()[source]¶
See
socketserver.BaseServer.shutdown()
.
- fileno()[source]¶
See
socketserver.BaseServer.fileno()
.
Using a connection¶
- class websockets.sync.server.ServerConnection(socket, protocol, *, ping_interval=20, ping_timeout=20, close_timeout=10, max_queue=16)[source]¶
threading
implementation of a WebSocket server connection.ServerConnection
providesrecv()
andsend()
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.The
ping_interval
,ping_timeout
,close_timeout
, andmax_queue
arguments have the same meaning as inserve()
.- Parameters:
socket (socket.socket) – Socket connected to a WebSocket client.
protocol (ServerProtocol) – Sans-I/O connection.
- for ... in __iter__()[source]¶
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, decode=None)[source]¶
Receive the next message.
When the connection is closed,
recv()
raisesConnectionClosed
. Specifically, it raisesConnectionClosedOK
after a normal closure andConnectionClosedError
after a protocol error or a network failure. This is how you detect the end of the message stream.If
timeout
isNone
, block until a message is received. Iftimeout
is set, wait up totimeout
seconds for a message to be received and return it, else raiseTimeoutError
. Iftimeout
is0
or negative, check if a message has been received already and return it, else raiseTimeoutError
.If the message is fragmented, wait until all fragments are received, reassemble them, and return the whole message.
- Parameters:
- 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:
ConnectionClosed – When the connection is closed.
ConcurrencyError – If two threads call
recv()
orrecv_streaming()
concurrently.
- Return type:
- 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 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()
.- Parameters:
decode (bool | None) – Set this flag to override the default behavior of returning
str
orbytes
. 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:
ConnectionClosed – When the connection is closed.
ConcurrencyError – If two threads call
recv()
orrecv_streaming()
concurrently.
- Return type:
- 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
, ormemoryview
) 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
, ormemoryview
) 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 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 really want to send the keys of a dict-like object as fragments, call itskeys()
method and pass the result tosend()
.)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]) – Message to send.
- Raises:
ConnectionClosed – When the connection is closed.
ConcurrencyError – If the connection is sending a fragmented message.
TypeError – If
message
doesn’t have a supported type.
- close(code=CloseCode.NORMAL_CLOSURE, reason='')[source]¶
Perform the closing handshake.
close()
waits for the other end to complete the handshake, for the TCP connection to terminate, and for all incoming messages to be read withrecv()
.close()
is idempotent: it doesn’t do anything once the connection is closed.
- ping(data=None, ack_on_close=False)[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. Ifdata
isNone
, the payload is four random bytes.ack_on_close (bool) – 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 stillOPEN
to 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_event = ws.ping() pong_event.wait() # only if you want to wait for the pong
- 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:
- 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
andprocess_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:
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()
.
- 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()
.
- 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 handleConnectionClosed
exceptions.
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.
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.
HTTP Basic Authentication¶
websockets supports HTTP Basic Authentication according to RFC 7235 and RFC 7617.
- websockets.sync.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 withserve()
as follows:from websockets.sync.server import basic_auth, serve 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
orcheck_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], bool] | None) – Function that verifies credentials. It receives
username
andpassword
arguments and returns whether they’re valid.
- Raises:
TypeError – If
credentials
orcheck_credentials
is wrong.ValueError – If
credentials
andcheck_credentials
are both provided or both not provided.