Both sides (asyncio)

class websockets.asyncio.connection.Connection(protocol, *, ping_interval=20, ping_timeout=20, close_timeout=10, max_queue=16, write_limit=32768)[source]

asyncio implementation of a WebSocket connection.

Connection provides APIs shared between WebSocket servers and clients.

You shouldn’t use it directly. Instead, use ClientConnection or ServerConnection.

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: Literal[True]) str[source]
await recv(decode: Literal[False]) bytes
await recv(decode: bool | None = None) str | bytes

Receive the next message.

When the connection is closed, recv() raises ConnectionClosed. Specifically, it raises ConnectionClosedOK after a normal closure and ConnectionClosedError 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 of recv() will return the next message.

This makes it possible to enforce a timeout by wrapping recv() in timeout() or wait_for().

When the message is fragmented, recv() waits until all fragments are received, reassembles them, and returns the whole message.

Parameters:

decode – Set this flag to override the default behavior of returning str or bytes. 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:
async for ... in recv_streaming(decode: Literal[True]) AsyncIterator[str][source]
async for ... in recv_streaming(decode: Literal[False]) AsyncIterator[bytes]
async for ... in recv_streaming(decode: bool | None = None) AsyncIterator[str | bytes]

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() or recv_streaming() will raise ConcurrencyError, making the connection unusable.

recv_streaming() raises the same exceptions as recv().

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 with close().

Parameters:

decode – Set this flag to override the default behavior of returning str or bytes. 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:
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, or memoryview) 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, or memoryview) 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 else send() will raise a TypeError 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 its keys() method and pass the result to send().)

Canceling send() is discouraged. Instead, you should close the connection with close(). Indeed, there are only two situations where send() may yield control to the event loop and then get canceled; in both cases, close() has the same effect and is more clear:

  1. 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.

  2. 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() raises ConnectionClosed. Specifically, it raises ConnectionClosedOK after a normal connection closure and ConnectionClosedError after a protocol error or a network failure.

Parameters:

message (str | bytes | Iterable[str | bytes] | AsyncIterable[str | bytes]) – Message to send.

Raises:
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.

Parameters:
  • code (int) – WebSocket close code.

  • reason (str) – WebSocket close reason.

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. If data is None, 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:

Awaitable[float]

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:

id: UUID

Unique identifier of the connection. Useful in logs.

logger: Logger | LoggerAdapter

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 is 0.

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() or send() and handle ConnectionClosed exceptions.

The following attributes are available after the opening handshake, once the WebSocket connection is open:

request: Request | None

Opening handshake request.

response: Response | None

Opening handshake response.

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.