Server (Sans-I/O)¶
- class websockets.server.ServerProtocol(*, origins=None, extensions=None, subprotocols=None, select_subprotocol=None, state=State.CONNECTING, max_size=1048576, logger=None)[source]¶
Sans-I/O implementation of a WebSocket server connection.
- Parameters:
origins (Sequence[Origin | None] | None) – Acceptable values of the
Origin
header; includeNone
in the list if the lack of an origin is acceptable. This is useful for defending against Cross-Site WebSocket Hijacking attacks.extensions (list[websockets.extensions.base.Extension]) – List of supported extensions, in order in which they should be tried.
subprotocols (Sequence[Subprotocol] | None) – List of supported subprotocols, in order of decreasing preference.
select_subprotocol (Callable[[ServerProtocol, Sequence[Subprotocol]], Subprotocol | None] | None) – Callback for selecting a subprotocol among those supported by the client and the server. It has the same signature as the
select_subprotocol()
method, including aServerProtocol
instance as first argument.state (State) – Initial state of the WebSocket connection.
max_size (int | None) – Maximum size of incoming messages in bytes;
None
disables the limit.logger (Union[logging.Logger, logging.LoggerAdapter]) – Logger for this connection; defaults to
logging.getLogger("websockets.server")
; see the logging guide for details.
- receive_data(data)[source]¶
Receive data from the network.
After calling this method:
You must call
data_to_send()
and send this data to the network.You should call
events_received()
and process resulting events.
- 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:
You must call
data_to_send()
and send this data to the network; it will return[b""]
, signaling the end of the stream, or[]
.You aren’t expected to call
events_received()
; it won’t return any new events.
receive_eof()
is idempotent.
- accept(request)[source]¶
Create a handshake response to accept the connection.
If the handshake request is valid and the handshake successful,
accept()
returns an HTTP response with status code 101.Else, it returns an HTTP response with another status code. This rejects the connection, like
reject()
would.You must send the handshake response with
send_response()
.You may modify the response before sending it, typically by adding HTTP headers.
- Parameters:
request (websockets.http11.Request) – WebSocket handshake request received from the client.
- Returns:
WebSocket handshake response or HTTP response to send to the client.
- Return type:
- select_subprotocol(subprotocols)[source]¶
Pick a subprotocol among those offered by the client.
If several subprotocols are supported by both the client and the server, pick the first one in the list declared the server.
If the server doesn’t support any subprotocols, continue without a subprotocol, regardless of what the client offers.
If the server supports at least one subprotocol and the client doesn’t offer any, abort the handshake with an HTTP 400 error.
You provide a
select_subprotocol
argument toServerProtocol
to override this logic. For example, you could accept the connection even if client doesn’t offer a subprotocol, rather than reject it.Here’s how to negotiate the
chat
subprotocol if the client supports it and continue without a subprotocol otherwise:def select_subprotocol(protocol, subprotocols): if "chat" in subprotocols: return "chat"
- Parameters:
subprotocols (Sequence[websockets.typing.Subprotocol]) – List of subprotocols offered by the client.
- Returns:
Selected subprotocol, if a common subprotocol was found.
None
to continue without a subprotocol.- Raises:
NegotiationError – Custom implementations may raise this exception to abort the handshake with an HTTP 400 error.
- Return type:
Optional[websockets.typing.Subprotocol]
- 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 may modify the response before sending it, for example by changing HTTP headers.
- Parameters:
status (Union[http.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:
- send_response(response)[source]¶
Send a handshake response to the client.
- Parameters:
response (websockets.http11.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 toFalse
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:
code (Optional[int]) – close code.
reason (str) – close reason.
- Raises:
ProtocolError – 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[Union[websockets.http11.Request, websockets.http11.Response, websockets.frames.Frame]]
- data_to_send()[source]¶
Obtain data to send to the network.
Call this method immediately after any of the
receive_*()
,send_*()
, orfail()
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_*()
,send_close()
, orfail()
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
WebSocket protocol objects also provide these attributes:
- id: uuid.UUID¶
Unique identifier of the connection. Useful in logs.
- logger: LoggerLike¶
Logger for this connection.
- property state: websockets.protocol.State¶
State of the WebSocket connection.
Defined in 4.1, 4.2, 7.1.3, and 7.1.4 of RFC 6455.
The following attributes are available after the opening handshake, once the WebSocket connection is open:
- handshake_exc: Exception | None¶
Exception to raise if the opening handshake failed.
None
if the opening handshake succeeded.
The following attributes are available after the closing handshake, once the WebSocket connection is closed:
- property close_code: int | None¶
-
None
if the connection isn’t closed yet.
- property close_reason: str | None¶
-
None
if the connection isn’t closed yet.
- property close_exc: websockets.exceptions.ConnectionClosed¶
Exception to raise when trying to interact with a closed connection.
Don’t raise this exception while the connection
state
isCLOSING
; wait until it’sCLOSED
.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.