Client (asyncio
)¶
Opening a connection¶
- await websockets.asyncio.client.connect(uri, *, origin=None, extensions=None, subprotocols=None, compression='deflate', additional_headers=None, user_agent_header='Python/3.10 websockets/15.1.dev2+gbb78c20', proxy=True, process_exception=<function process_exception>, open_timeout=10, ping_interval=20, ping_timeout=20, close_timeout=10, max_size=1048576, max_queue=16, write_limit=32768, logger=None, create_connection=None, **kwargs)[source]¶
Connect to the WebSocket server at
uri
.This coroutine returns a
ClientConnection
instance, which you can use to send and receive messages.connect()
may be used as an asynchronous context manager:from websockets.asyncio.client import connect async with connect(...) as websocket: ...
The connection is closed automatically when exiting the context.
connect()
can be used as an infinite asynchronous iterator to reconnect automatically on errors:async for websocket in connect(...): try: ... except websockets.exceptions.ConnectionClosed: continue
If the connection fails with a transient error, it is retried with exponential backoff. If it fails with a fatal error, the exception is raised, breaking out of the loop.
The connection is closed automatically after each iteration of the loop.
- Parameters:
uri (str) – URI of the WebSocket server.
origin (Origin | None) – Value of the
Origin
header, for servers that require it.extensions (Sequence[ClientExtensionFactory] | 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.
compression (str | None) – The “permessage-deflate” extension is enabled by default. Set
compression
toNone
to disable it. See the compression guide for details.additional_headers (HeadersLike | None) – Arbitrary HTTP headers to add to the handshake request.
user_agent_header (str | None) – Value of the
User-Agent
request header. It defaults to"Python/x.y.z websockets/X.Y"
. Setting it toNone
removes the header.proxy (str | Literal[True] | None) – If a proxy is configured, it is used by default. Set
proxy
toNone
to disable the proxy or to the address of a proxy to override the system configuration. See the proxy docs for details.process_exception (Callable[[Exception], Exception | None]) – When reconnecting automatically, tell whether an error is transient or fatal. The default behavior is defined by
process_exception()
. Refer to its documentation for details.open_timeout (float | None) – Timeout for opening the connection 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 the connection 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.write_limit (int | tuple[int, int | None]) – High-water mark of write buffer in bytes. It is passed to
set_write_buffer_limits()
. It defaults to 32 KiB. You may pass a(high, low)
tuple to set the high-water and low-water marks.logger (LoggerLike | None) – Logger for this client. It defaults to
logging.getLogger("websockets.client")
. See the logging guide for details.create_connection (type[ClientConnection] | None) – Factory for the
ClientConnection
managing the connection. Set it to a wrapper or a subclass to customize connection handling.
Any other keyword arguments are passed to the event loop’s
create_connection()
method.For example:
You can set
ssl
to aSSLContext
to enforce TLS settings. When connecting to awss://
URI, ifssl
isn’t provided, a TLS context is created withcreate_default_context()
.You can set
server_hostname
to override the host name fromuri
in the TLS handshake.You can set
host
andport
to connect to a different host and port from those found inuri
. This only changes the destination of the TCP connection. The host name fromuri
is still used in the TLS handshake for secure connections and in theHost
header.You can set
sock
to provide a preexisting TCP socket. You may callsocket.create_connection()
(not to be confused with the event loop’screate_connection()
method) to create a suitable client socket and customize it.
When using a proxy:
Prefix keyword arguments with
proxy_
for configuring TLS between the client and an HTTPS proxy:proxy_ssl
,proxy_server_hostname
,proxy_ssl_handshake_timeout
, andproxy_ssl_shutdown_timeout
.Use the standard keyword arguments for configuring TLS between the proxy and the WebSocket server:
ssl
,server_hostname
,ssl_handshake_timeout
, andssl_shutdown_timeout
.Other keyword arguments are used only for connecting to the proxy.
- Raises:
InvalidURI – If
uri
isn’t a valid WebSocket URI.InvalidProxy – If
proxy
isn’t a valid proxy.OSError – If the TCP connection fails.
InvalidHandshake – If the opening handshake fails.
TimeoutError – If the opening handshake times out.
- await websockets.asyncio.client.unix_connect(path=None, uri=None, **kwargs)[source]¶
Connect to a WebSocket server listening on a Unix socket.
This function accepts the same keyword arguments as
connect()
.It’s only available on Unix.
It’s mainly useful for debugging servers listening on Unix sockets.
- websockets.asyncio.client.process_exception(exc)[source]¶
Determine whether a connection error is retryable or fatal.
When reconnecting automatically with
async for ... in connect(...)
, if a connection attempt fails,process_exception()
is called to determine whether to retry connecting or to raise the exception.This function defines the default behavior, which is to retry on:
EOFError
,OSError
,asyncio.TimeoutError
: network errors;InvalidStatus
when 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_exception
argument ofconnect()
.Return
None
if 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 theINFO
level.Return an exception, either
exc
or 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.
Using a connection¶
- class websockets.asyncio.client.ClientConnection(protocol, *, ping_interval=20, ping_timeout=20, close_timeout=10, max_queue=16, write_limit=32768)[source]¶
asyncio
implementation of a WebSocket client connection.ClientConnection
providesrecv()
andsend()
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) 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
,max_queue
, andwrite_limit
arguments have the same meaning as inconnect()
.- Parameters:
protocol (ClientProtocol) – Sans-I/O connection.
- async for ... in __aiter__()[source]¶
Iterate on incoming messages.
The iterator calls
recv()
and yields messages asynchronously 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.
- await recv(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.Canceling
recv()
is safe. There’s no risk of losing data. The next invocation ofrecv()
will return the next message.This makes it possible to enforce a timeout by wrapping
recv()
intimeout()
orwait_for()
.When the message is fragmented,
recv()
waits until all fragments are received, reassembles them, and returns the whole message.- Parameters:
decode (bool | None) – Set this flag to override the default behavior of returning
str
orbytes
. See below for details.- 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 coroutines call
recv()
orrecv_streaming()
concurrently.
- Return type:
- async 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 asynchronous 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()
.Canceling
recv_streaming()
before receiving the first frame is safe. Canceling it after receiving one or more frames leaves the iterator in a partially consumed state, making the connection unusable. Instead, you should close the connection withclose()
.- 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 coroutines call
recv()
orrecv_streaming()
concurrently.
- Return type:
- await 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 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 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()
.)Canceling
send()
is discouraged. Instead, you should close the connection withclose()
. Indeed, there are only two situations wheresend()
may yield control to the event loop and then get canceled; in both cases,close()
has the same effect and is more clear: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.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()
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] | AsyncIterable[str | bytes]) – Message to send.
- Raises:
ConnectionClosed – When the connection is closed.
TypeError – If
message
doesn’t have a supported type.
- 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.close()
is idempotent: it doesn’t do anything once the connection is closed.
- await wait_closed()[source]¶
Wait until the connection is closed.
wait_closed()
waits for the closing handshake to complete and for the TCP connection to terminate.
- 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
- 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.- Returns:
A future that will be completed when the corresponding pong is received. You can ignore it if you don’t intend to wait. The result of the future is the latency of the connection in seconds.
pong_waiter = await ws.ping() # only if you want to wait for the corresponding pong latency = await pong_waiter
- 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:
- await 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.
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()
.
- latency: float¶
Latency of the connection, in seconds.
Latency is defined as the round-trip time of the connection. It is measured by sending a Ping frame and waiting for a matching Pong frame. Before the first measurement,
latency
is0
.By default, websockets enables a keepalive mechanism that sends Ping frames automatically at regular intervals. You can also send Ping frames and measure latency with
ping()
.
- 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.