Both sides (threading)¶
- class websockets.sync.connection.Connection(socket, protocol, *, close_timeout=10, max_queue=16)[source]¶
threadingimplementation of a WebSocket connection.Connectionprovides APIs shared between WebSocket servers and clients.You shouldn’t use it directly. Instead, use
ClientConnectionorServerConnection.- for ... in __iter__()[source]¶
Iterate on incoming messages.
The iterator calls
recv()and yields messages in an infinite loop.It exits when the connection is closed normally. It raises a
ConnectionClosedErrorexception after a protocol error or a network failure.
- recv(timeout=None, decode=None)[source]¶
Receive the next message.
When the connection is closed,
recv()raisesConnectionClosed. Specifically, it raisesConnectionClosedOKafter a normal closure andConnectionClosedErrorafter a protocol error or a network failure. This is how you detect the end of the message stream.If
timeoutisNone, block until a message is received. Iftimeoutis set and no message is received withintimeoutseconds, raiseTimeoutError. Settimeoutto0to check if a message was already received.If the message is fragmented, wait until all fragments are received, reassemble them, and return the whole message.
- Parameters:
- Returns:
A string (
str) for a Text frame or a bytestring (bytes) for a Binary frame.You may override this behavior with the
decodeargument:Set
decode=Falseto 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=Trueto 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 threads call
recv()orrecv_streaming()concurrently.
- Return type:
- 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 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().- Parameters:
decode (bool | None) – Set this flag to override the default behavior of returning
strorbytes. 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
decodeargument:Set
decode=Falseto 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=Trueto 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 threads call
recv()orrecv_streaming()concurrently.
- Return type:
- 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
textargument:Set
text=Trueto 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=Falseto 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 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 aTypeErrorand 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().)When the connection is closed,
send()raisesConnectionClosed. Specifically, it raisesConnectionClosedOKafter a normal connection closure andConnectionClosedErrorafter a protocol error or a network failure.- Parameters:
message (str | bytes | Iterable[str | bytes]) – Message to send.
- Raises:
ConnectionClosed – When the connection is closed.
ConcurrencyError – If the connection is sending a fragmented message.
TypeError – If
messagedoesn’t have a supported type.
- close(code=CloseCode.NORMAL_CLOSURE, reason='')[source]¶
Perform the closing handshake.
close()waits for the other end to complete the handshake, for the TCP connection to terminate, and for all incoming messages to be read withrecv().close()is idempotent: it doesn’t do anything once the connection is closed.
- 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
strwill be encoded to UTF-8. IfdataisNone, the payload is four random bytes.- Returns:
An event that will be set when the corresponding pong is received. You can ignore it if you don’t intend to wait.
pong_event = ws.ping() pong_event.wait() # only if you want to wait for the pong
- 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:
- 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
strwill be encoded to UTF-8.- Raises:
ConnectionClosed – When the connection is closed.
WebSocket connection objects also provide these attributes:
- 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().
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.
Noneif no subprotocol was negotiated.