Ping pong websocket python

Client ( threading )#

websockets.sync.client. connect ( uri , * , sock = None , ssl_context = None , server_hostname = None , origin = None , extensions = None , subprotocols = None , additional_headers = None , user_agent_header = ‘Python/x.y.z websockets/X.Y’ , compression = ‘deflate’ , open_timeout = 10 , close_timeout = 10 , max_size = 2**20 , logger = None , create_connection = None ) [source] # Connect to the WebSocket server at uri . This function returns a ClientConnection instance, which you can use to send and receive messages. connect() may be used as a context manager:

async with websockets.sync.client.connect(. ) as websocket: . 
  • uri (str) – URI of the WebSocket server.
  • sock (socket|None) – Preexisting TCP socket. sock overrides the host and port from uri . You may call socket.create_connection() to create a suitable TCP socket.
  • ssl_context (SSLContext|None) – Configuration for enabling TLS on the connection.
  • server_hostname (str|None) – Host name for the TLS handshake. server_hostname overrides the host name from uri .
  • 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.
  • 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 to None removes the header.
  • compression (str|None) – The “permessage-deflate” extension is enabled by default. Set compression to None to disable it. See the compression guide for details.
  • open_timeout (float|None) – Timeout for opening the connection in seconds. None disables the timeout.
  • 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.
  • logger (Logger|LoggerAdapter|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.
  • InvalidURI – If uri isn’t a valid WebSocket URI.
  • OSError – If the TCP connection fails.
  • InvalidHandshake – If the opening handshake fails.
  • TimeoutError – If the opening handshake times out.
Читайте также:  Get stack trace method java

Connect to a WebSocket server listening on a Unix socket.

This function is identical to connect() , except for the additional path argument. It’s only available on Unix.

It’s mainly useful for debugging servers listening on Unix sockets.

  • path (str|None) – File system path to the Unix socket.
  • uri (str|None) – URI of the WebSocket server. uri defaults to ws://localhost/ or, when a ssl_context is provided, to wss://localhost/ .

Using a connection#

class websockets.sync.client. ClientConnection ( socket , protocol , * , close_timeout = 10 ) [source] #

Threaded implementation of a WebSocket client connection.

ClientConnection provides recv() and send() methods for receiving and sending messages.

It supports iteration to receive messages:

for message in websocket: 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.

  • socket (socket.socket) – Socket connected to a WebSocket server.
  • protocol (ClientProtocol) – Sans-I/O connection.
  • close_timeout (Optional[float]) – Timeout for closing the connection in seconds.

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 ConnectionClosedError exception after a protocol error or a network failure.

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.

If timeout is None , block until a message is received. If timeout is set and no message is received within timeout seconds, raise TimeoutError . Set timeout to 0 to check if a message was already received.

Читайте также:  Php foreach узнать номер итерации

If the message is fragmented, wait until all fragments are received, reassemble them, and return the whole message.

A string ( str ) for a Text frame or a bytestring ( bytes ) for a Binary frame.

Receive the next message frame by frame.

If the message is fragmented, yield each fragment as it is received. The iterator must be fully consumed, or else the connection will become unusable.

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

An iterator of strings ( str ) for a Text frame or bytestrings ( bytes ) for a Binary frame.

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.

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

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.

  • ConnectionClosed – When the connection is closed.
  • RuntimeError – If a connection is busy sending a fragmented message.
  • TypeError – If message doesn’t have a supported type.

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

Читайте также:  Php display error to file

close() is idempotent: it doesn’t do anything once the connection is closed.

  • code (int) – WebSocket close code.
  • reason (str) – WebSocket close reason.

A ping may serve as a keepalive or as a check that the remote endpoint received all messages up to this point

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.

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 
  • ConnectionClosed – When the connection is closed.
  • RuntimeError – If another ping was sent with the same data and the corresponding pong wasn’t received yet.

An unsolicited pong may serve as a unidirectional heartbeat.

data (str | bytes) – Payload of the pong. A str will be encoded to UTF-8.

WebSocket connection objects also provide these attributes:

Unique identifier of the connection. Useful in logs.

Logger for this connection.

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

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:

Opening handshake request.

Opening handshake response.

Subprotocol negotiated during the opening handshake.

None if no subprotocol was negotiated.

Источник

Оцените статью