Client (Sans-I/O)¶
- class websockets.client.ClientProtocol(uri, *, origin=None, extensions=None, subprotocols=None, state=State.CONNECTING, max_size=1048576, logger=None)¶
Sans-I/O implementation of a WebSocket client connection.
- Parameters:
uri (WebSocketURI) – URI of the WebSocket server, parsed with
parse_uri().origin (Origin | None) – Value of the
Originheader. This is useful when connecting to a server that validates theOriginheader to defend against Cross-Site WebSocket Hijacking attacks.extensions (Sequence[ClientExtensionFactory] | None) – 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.
state (State) – Initial state of the WebSocket connection.
max_size (int | None | tuple[int | None, int | None]) – Maximum size of incoming messages in bytes.
Nonedisables the limit. You may pass a(max_message_size, max_fragment_size)tuple to set different limits for messages and fragments when you expect long messages sent in short fragments.logger (LoggerLike | None) – Logger for this connection; defaults to
logging.getLogger("websockets.client"); see the logging guide for details.
- receive_data(data)¶
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()¶
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.
- connect()¶
Create a handshake request to open a connection.
You must send the handshake request with
send_request().You can modify it before sending it, for example to add HTTP headers.
- Returns:
WebSocket handshake request event to send to the server.
- Return type:
- send_request(request)¶
Send a handshake request to the server.
- Parameters:
request (Request) – WebSocket handshake request event.
- send_continuation(data, fin)¶
Send a Continuation frame.
- Parameters:
- Raises:
ProtocolError – If a fragmented message isn’t in progress.
- send_text(data, fin=True)¶
Send a Text frame.
- Parameters:
data (bytes | bytearray | memoryview) – payload containing text encoded with UTF-8.
fin (bool) – FIN bit; set it to
Falseif this is the first frame of a fragmented message.
- Raises:
ProtocolError – If a fragmented message is in progress.
- send_binary(data, fin=True)¶
Send a Binary frame.
- Parameters:
data (bytes | bytearray | memoryview) – payload containing arbitrary binary data.
fin (bool) – FIN bit; set it to
Falseif this is the first frame of a fragmented message.
- Raises:
ProtocolError – If a fragmented message is in progress.
- send_close(code=None, reason='')¶
Send a Close frame.
- Parameters:
- Raises:
ProtocolError – If the code isn’t valid or if a reason is provided without a code.
- send_ping(data)¶
Send a Ping frame.
- Parameters:
data (bytes | bytearray | memoryview) – payload containing arbitrary binary data.
- send_pong(data)¶
Send a Pong frame.
- Parameters:
data (bytes | bytearray | memoryview) – payload containing arbitrary binary data.
- fail(code, reason='')¶
Fail the WebSocket connection.
- Parameters:
- Raises:
ProtocolError – If the code isn’t valid.
- events_received()¶
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.
- data_to_send()¶
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_EOFsignals the end of the data stream. When you receive it, half-close the TCP connection.
- close_expected()¶
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:
WebSocket protocol objects also provide these attributes:
- logger: Logger | LoggerAdapter[Any]¶
Logger for this connection.
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.
Noneif the opening handshake succeeded.
The following attributes are available after the closing handshake, once the WebSocket connection is closed:
- property close_code: int | None¶
WebSocket close code received from the remote endpoint.
Noneif the connection isn’t closed yet.
- property close_reason: str | None¶
WebSocket close reason received from the remote endpoint.
Noneif 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
stateisCLOSING; 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.
- websockets.client.process_exception(exc)¶
Determine whether a connection error is retryable or fatal.
When reconnecting automatically with
async for ... in connect(...)(asyncio,trio) orfor ... in reconnect(...)(threading), whenever a connection attempt fails,process_exception()determines whether to retry connecting or to raise the exception.This function defines the default behavior, which is to retry on:
OSErrorandasyncio.TimeoutError: network errors;InvalidMessagewhen it stems from anEOFError: also network errors;InvalidStatuswhen the status code is 500, 502, 503, or 504: server or proxy errors.
All other exceptions are considered fatal.
You can change this behavior with the
process_exceptionargument ofconnect()(asyncio),connect()(trio), orreconnect()(threading).Return
Noneif the exception is retryable i.e. when the error could be transient and trying to reconnect with the same parameters could succeed. The exception will be logged at theINFOlevel.Return an exception, either
excor a new exception, if the exception is fatal i.e. when trying to reconnect will most likely produce the same error. That exception will be raised, breaking out of the retry loop.