Client¶
Opening a connection¶
- await websockets.client.connect(uri, *, create_protocol=None, ping_interval=20, ping_timeout=20, close_timeout=None, max_size=1048576, max_queue=32, read_limit=65536, write_limit=65536, loop=None, compression='deflate', origin=None, extensions=None, subprotocols=None, extra_headers=None, **kwargs)¶
Connect to the WebSocket server at the given
uri.Awaiting
connect()yields aWebSocketClientProtocolwhich can then be used to send and receive messages.connect()can also be used as a asynchronous context manager:async with connect(...) as websocket: ...
In that case, the connection is closed when exiting the context.
connect()is a wrapper around the event loop’screate_connection()method. Unknown keyword arguments are passed tocreate_connection().For example, you can set the
sslkeyword argument to aSSLContextto enforce some TLS settings. When connecting to awss://URI, if this argument isn’t provided explicitly,ssl.create_default_context()is called to create a context.You can connect to a different host and port from those found in
uriby settinghostandportkeyword arguments. This only changes the destination of the TCP connection. The host name fromuriis still used in the TLS handshake for secure connections and in theHostHTTP header.create_protocoldefaults toWebSocketClientProtocol. It may be replaced by a wrapper or a subclass to customize the protocol that manages the connection.The behavior of
ping_interval,ping_timeout,close_timeout,max_size,max_queue,read_limit, andwrite_limitis described inWebSocketClientProtocol.connect()also accepts the following optional arguments:compressionis a shortcut to configure compression extensions; by default it enables the “permessage-deflate” extension; set it toNoneto disable compression.originsets the Origin HTTP header.extensionsis a list of supported extensions in order of decreasing preference.subprotocolsis a list of supported subprotocols in order of decreasing preference.extra_headerssets additional HTTP request headers; it can be aHeadersinstance, aMapping, or an iterable of(name, value)pairs.
- Raises:
InvalidURI – if
uriis invalidInvalidHandshake – if the opening handshake fails
- await websockets.client.unix_connect(path, uri='ws://localhost/', **kwargs)[source]¶
Similar to
connect(), but for connecting to a Unix socket.This function calls 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(*, origin=None, extensions=None, subprotocols=None, extra_headers=None, **kwargs)[source]¶
Protocolsubclass implementing a WebSocket client.performs the opening handshake to establish the connection;
provides
recv()andsend()coroutines for receiving and sending messages;deals with control frames automatically;
performs the closing handshake to terminate the connection.
WebSocketClientProtocolsupports asynchronous iteration:async for message in websocket: await process(message)
The iterator yields incoming messages. It exits normally when the connection is closed with the close code 1000 (OK) or 1001 (going away). It raises a
ConnectionClosedErrorexception when the connection is closed with any other code.Once the connection is open, a Ping frame is sent every
ping_intervalseconds. This serves as a keepalive. It helps keeping the connection open, especially in the presence of proxies with short timeouts on inactive connections. Setping_intervaltoNoneto disable this behavior.If the corresponding Pong frame isn’t received within
ping_timeoutseconds, the connection is considered unusable and is closed with code 1011. This ensures that the remote endpoint remains responsive. Setping_timeouttoNoneto disable this behavior.The
close_timeoutparameter defines a maximum wait time for completing the closing handshake and terminating the TCP connection. For legacy reasons,close()completes in at most5 * close_timeoutseconds.close_timeoutneeds to be a parameter of the protocol because websockets usually callsclose()implicitly upon exit whenconnect()is used as a context manager.To apply a timeout to any other API, wrap it in
wait_for().The
max_sizeparameter enforces the maximum size for incoming messages in bytes. The default value is 1 MiB.Nonedisables the limit. If a message larger than the maximum size is received,recv()will raiseConnectionClosedErrorand the connection will be closed with code 1009.The
max_queueparameter sets the maximum length of the queue that holds incoming messages. The default value is32.Nonedisables the limit. Messages are added to an in-memory queue when they’re received; thenrecv()pops from that queue. In order to prevent excessive memory consumption when messages are received faster than they can be processed, the queue must be bounded. If the queue fills up, the protocol stops processing incoming data untilrecv()is called. In this situation, various receive buffers (at least inasyncioand in the OS) will fill up, then the TCP receive window will shrink, slowing down transmission to avoid packet loss.Since Python can use up to 4 bytes of memory to represent a single character, each connection may use up to
4 * max_size * max_queuebytes of memory to store incoming messages. By default, this is 128 MiB. You may want to lower the limits, depending on your application’s requirements.The
read_limitargument sets the high-water limit of the buffer for incoming bytes. The low-water limit is half the high-water limit. The default value is 64 KiB, half of asyncio’s default (based on the current implementation ofStreamReader).The
write_limitargument sets the high-water limit of the buffer for outgoing bytes. The low-water limit is a quarter of the high-water limit. The default value is 64 KiB, equal to asyncio’s default (based on the current implementation ofFlowControlMixin).As soon as the HTTP request and response in the opening handshake are processed:
the request path is available in the
pathattribute;the request and response HTTP headers are available in the
request_headersandresponse_headersattributes, which areHeadersinstances.
If a subprotocol was negotiated, it’s available in the
subprotocolattribute.Once the connection is closed, the code is available in the
close_codeattribute and the reason inclose_reason.All attributes must be treated as read-only.
- local_address¶
Local address of the connection as a
(host, port)tuple.When the connection isn’t open,
local_addressisNone.
- remote_address¶
Remote address of the connection as a
(host, port)tuple.When the connection isn’t open,
remote_addressisNone.
- open¶
Truewhen the connection is usable.It may be used to detect disconnections. However, this approach is discouraged per the EAFP principle.
When
openisFalse, using the connection raises aConnectionClosedexception.
- closed¶
Trueonce the connection is closed.Be aware that both
openandclosedareFalseduring the opening and closing sequences.
- path¶
Path of the HTTP request.
Available once the connection is open.
- request_headers¶
HTTP request headers as a
Headersinstance.Available once the connection is open.
- response_headers¶
HTTP response headers as a
Headersinstance.Available once the connection is open.
- subprotocol¶
Subprotocol, if one was negotiated.
Available once the connection is open.
- close_code¶
WebSocket close code.
Available once the connection is closed.
- close_reason¶
WebSocket close reason.
Available once the connection is closed.
- await recv()¶
Receive the next message.
Return a
strfor a text frame andbytesfor a binary frame.When the end of the message stream is reached,
recv()raisesConnectionClosed. Specifically, it raisesConnectionClosedOKafter a normal connection closure andConnectionClosedErrorafter a protocol error or a network failure.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 wrappingrecv()inwait_for().- Raises:
ConnectionClosed – when the connection is closed
RuntimeError – if two coroutines call
recv()concurrently
- Return type:
- await send(message)¶
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. :rtype:Nonesend()also accepts an iterable or an asynchronous iterable of strings, bytestrings, or bytes-like objects. In that case the message is fragmented. 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 aTypeErrorand the connection will be closed.send()rejects dict-like objects because this is often an error. If you wish 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: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.messageis an asynchronous iterator that yields control. Stopping in the middle of a fragmented message will cause a protocol error. Closing the connection has the same effect.
- Raises:
TypeError – for unsupported inputs
- await ping(data=None)¶
Send a ping.
Return a
Futurethat will be completed when the corresponding pong is received. You can ignore it if you don’t intend to wait.A ping may serve as a keepalive or as a check that the remote endpoint received all messages up to this point:
pong_waiter = await ws.ping() await pong_waiter # only if you want to wait for the pong
By default, the ping contains four random bytes. This payload may be overridden with the optional
dataargument which must be a string (which will be encoded to UTF-8) or a bytes-like object.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.
- await pong(data=b'')¶
Send a pong.
An unsolicited pong may serve as a unidirectional heartbeat.
The payload may be set with the optional
dataargument which must be a string (which will be encoded to UTF-8) or a bytes-like object.Canceling
pong()is discouraged for the same reason asping().- Return type:
- await close(code=1000, reason='')¶
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();close()already does it.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 close the TCP connection.