Client#
asyncio#
Opening a connection#
- await websockets.client.connect(uri, *, create_protocol=None, logger=None, compression='deflate', origin=None, extensions=None, subprotocols=None, extra_headers=None, user_agent_header='Python/x.y.z websockets/X.Y', open_timeout=10, ping_interval=20, ping_timeout=20, close_timeout=10, max_size=2**20, max_queue=2**5, read_limit=2**16, write_limit=2**16, **kwds)[source]#
Connect to the WebSocket server at
uri
.Awaiting
connect()
yields aWebSocketClientProtocol
which can then be used to send and receive messages.connect()
can be used as a asynchronous context manager:async with websockets.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 websockets.connect(...): try: ... except websockets.ConnectionClosed: continue
The connection is closed automatically after each iteration of the loop.
If an error occurs while establishing the connection,
connect()
retries with exponential backoff. The backoff delay starts at three seconds and increases up to one minute.If an error occurs in the body of the loop, you can handle the exception and
connect()
will reconnect with the next iteration; or you can let the exception bubble up and break out of the loop. This lets you decide which errors trigger a reconnection and which errors are fatal.- Parameters:
uri (str) – URI of the WebSocket server.
create_protocol (Optional[Callable[[Any], WebSocketClientProtocol]]) – factory for the
asyncio.Protocol
managing the connection; defaults toWebSocketClientProtocol
; may be set to a wrapper or a subclass to customize connection handling.logger (Optional[LoggerLike]) – logger for this connection; defaults to
logging.getLogger("websockets.client")
; see the logging guide for details.compression (Optional[str]) – shortcut that enables the “permessage-deflate” extension by default; may be set to
None
to disable compression; see the compression guide for details.origin (Optional[Origin]) – value of the
Origin
header. This is useful when connecting to a server that validates theOrigin
header to defend against Cross-Site WebSocket Hijacking attacks.extensions (Optional[Sequence[ClientExtensionFactory]]) – list of supported extensions, in order in which they should be tried.
subprotocols (Optional[Sequence[Subprotocol]]) – list of supported subprotocols, in order of decreasing preference.
extra_headers (Optional[HeadersLike]) – arbitrary HTTP headers to add to the request.
user_agent_header (Optional[str]) – value of the
User-Agent
request header; defaults to"Python/x.y.z websockets/X.Y"
;None
removes the header.open_timeout (Optional[float]) – timeout for opening the connection in seconds;
None
to disable the timeout
See
WebSocketCommonProtocol
for the documentation ofping_interval
,ping_timeout
,close_timeout
,max_size
,max_queue
,read_limit
, andwrite_limit
.Any other keyword arguments are passed 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
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.
- Returns:
WebSocket connection.
- Return type:
- Raises:
InvalidURI – if
uri
isn’t a valid WebSocket URI.InvalidHandshake – if the opening handshake fails.
TimeoutError – if the opening handshake times out.
- await websockets.client.unix_connect(path, uri='ws://localhost/', *, create_protocol=None, logger=None, compression='deflate', origin=None, extensions=None, subprotocols=None, extra_headers=None, user_agent_header='Python/x.y.z websockets/X.Y', open_timeout=10, ping_interval=20, ping_timeout=20, close_timeout=10, max_size=2**20, max_queue=2**5, read_limit=2**16, write_limit=2**16, **kwds)[source]#
Similar to
connect()
, but for connecting to a Unix socket.This function builds upon the event loop’s
create_unix_connection()
method.It is only available on Unix.
It’s mainly useful for debugging servers listening on Unix sockets.
Using a connection#
- class websockets.client.WebSocketClientProtocol(*, logger=None, origin=None, extensions=None, subprotocols=None, extra_headers=None, user_agent_header='Python/x.y.z websockets/X.Y', ping_interval=20, ping_timeout=20, close_timeout=10, max_size=2**20, max_queue=2**5, read_limit=2**16, write_limit=2**16)[source]#
WebSocket client connection.
WebSocketClientProtocol
providesrecv()
andsend()
coroutines for receiving and sending messages.It supports asynchronous iteration to receive incoming 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). It raises a
ConnectionClosedError
when the connection is closed with any other code.See
connect()
for the documentation oflogger
,origin
,extensions
,subprotocols
,extra_headers
, anduser_agent_header
.See
WebSocketCommonProtocol
for the documentation ofping_interval
,ping_timeout
,close_timeout
,max_size
,max_queue
,read_limit
, andwrite_limit
.- await recv()[source]#
Receive the next message.
When the connection is closed,
recv()
raisesConnectionClosed
. Specifically, it raisesConnectionClosedOK
after a normal connection 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 the next message. The next invocation ofrecv()
will return it.This makes it possible to enforce a timeout by wrapping
recv()
inwait_for()
.- Returns:
A string (
str
) for a Text frame. A bytestring (bytes
) for a Binary frame.- Return type:
- Raises:
ConnectionClosed – when the connection is closed.
RuntimeError – if two coroutines call
recv()
concurrently.
- await send(message)[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.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 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 (Union[Data, Iterable[Data], AsyncIterable[Data]) – 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. As a consequence, there’s no need to awaitwait_closed()
afterclose()
.close()
is idempotent: it doesn’t do anything once the connection is closed.Wrapping
close()
increate_task()
is safe, given that errors during connection termination aren’t particularly useful.Canceling
close()
is discouraged. If it takes too long, you can set a shorterclose_timeout
. If you don’t want to wait, let the Python process exit, then the OS will take care of closing the TCP connection.
- await wait_closed()[source]#
Wait until the connection is closed.
This coroutine is identical to the
closed
attribute, except it can be awaited.This can make it easier to detect connection termination, regardless of its cause, in tasks that interact with the WebSocket connection.
- await ping(data=None)[source]#
Send a Ping.
A ping may serve as a keepalive, as a check that the remote endpoint received all messages up to this point, or to measure
latency
.Canceling
ping()
is discouraged. Ifping()
doesn’t return immediately, it means the write buffer is full. If you don’t want to wait, you should close the connection.Canceling the
Future
returned byping()
has no effect.- Parameters:
data (Optional[Data]) – payload of the ping; a string will be encoded to UTF-8; or
None
to generate a payload containing 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
- Return type:
- 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.
- await pong(data=b'')[source]#
Send a Pong.
An unsolicited pong may serve as a unidirectional heartbeat.
Canceling
pong()
is discouraged. Ifpong()
doesn’t return immediately, it means the write buffer is full. If you don’t want to wait, you should close the connection.- Parameters:
data (Data) – payload of the pong; a string 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()
.None
if the TCP connection isn’t established yet.
- 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()
.None
if the TCP connection isn’t established yet.
- property open: bool#
True
when the connection is open;False
otherwise.This attribute may be used to detect disconnections. However, this approach is discouraged per the EAFP principle. Instead, you should handle
ConnectionClosed
exceptions.
- property closed: bool#
True
when the connection is closed;False
otherwise.Be aware that both
open
andclosed
areFalse
during the opening and closing sequences.
- latency: float#
Latency of the connection, in seconds.
This value is updated after sending a ping frame and receiving a matching pong frame. Before the first ping,
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()
.
The following attributes are available after the opening handshake, once the WebSocket connection is open:
- subprotocol: Subprotocol | None#
Subprotocol, if one was negotiated.
The following attributes are available after the closing handshake, once the WebSocket connection is closed:
- property close_code: int | None#
WebSocket close code, defined in section 7.1.5 of RFC 6455.
None
if the connection isn’t closed yet.
- property close_reason: str | None#
WebSocket close reason, defined in section 7.1.6 of RFC 6455.
None
if the connection isn’t closed yet.
Sans-I/O#
- class websockets.client.ClientConnection(wsuri, origin=None, extensions=None, subprotocols=None, state=State.CONNECTING, max_size=2**20, logger=None)[source]#
Sans-I/O implementation of a WebSocket client connection.
- Parameters:
wsuri (WebSocketURI) – URI of the WebSocket server, parsed with
parse_uri()
.origin (Optional[Origin]) – value of the
Origin
header. This is useful when connecting to a server that validates theOrigin
header to defend against Cross-Site WebSocket Hijacking attacks.extensions (Optional[Sequence[ClientExtensionFactory]]) – list of supported extensions, in order in which they should be tried.
subprotocols (Optional[Sequence[Subprotocol]]) – list of supported subprotocols, in order of decreasing preference.
state (State) – initial state of the WebSocket connection.
max_size (Optional[int]) – maximum size of incoming messages in bytes;
None
to disable the limit.logger (Optional[LoggerLike]) – logger for this connection; defaults to
logging.getLogger("websockets.client")
; 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.You aren’t expected to call
events_received()
; it won’t return any new events.
- Raises:
EOFError – if
receive_eof()
was called earlier.
- connect()[source]#
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)[source]#
Send a handshake request to the server.
- Parameters:
request (Request) – WebSocket handshake request event.
- send_continuation(data, fin)[source]#
Send a Continuation frame.
- Parameters:
- Raises:
ProtocolError – if a fragmented message isn’t in progress.
- send_text(data, fin=True)[source]#
Send a Text frame.
- Parameters:
- Raises:
ProtocolError – if a fragmented message is in progress.
- send_binary(data, fin=True)[source]#
Send a Binary frame.
- Parameters:
- Raises:
ProtocolError – if a fragmented message is in progress.
- send_close(code=None, reason='')[source]#
Send a Close frame.
- Parameters:
- Raises:
ProtocolError – if a fragmented message is being sent, 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:
- 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[Event]
- 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_*()
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:
- logger: LoggerLike#
Logger for this connection.
- property state: State#
WebSocket connection state.
Defined in 4.1, 4.2, 7.1.3, and 7.1.4 of RFC 6455.
- handshake_exc: Exception | None#
Exception to raise if the opening handshake failed.
None
if the opening handshake succeeded.
- property close_exc: 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.