Clients API

Network client module.


Abstract Base Classes

Network client interfaces definition module.

class easynetwork.clients.abc.AbstractAsyncNetworkClient

Bases: Generic[_T_SentPacket, _T_ReceivedPacket]

The base class for an asynchronous network client interface.

async __aenter__() Self

Calls wait_connected().

Return type:

Self

async __aexit__(exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None) None

Calls aclose().

abstractmethod is_connected() bool

Checks if the client initialization is finished.

See also

wait_connected() method.

Returns:

the client connection state.

Return type:

bool

abstractmethod async wait_connected() None

Finishes initializing the client, doing the asynchronous operations that could not be done in the constructor.

It is not needed to call it directly if the client is used as an asynchronous context manager:

async with client:  # wait_connected() has been called.
    ...

Warning

In the case of a cancellation, this would leave the client in an inconsistent state.

It is recommended to close the client in this case.

Can be safely called multiple times.

abstractmethod is_closing() bool

Checks if the client is closed or in the process of being closed.

If True, all future operations on the client object will raise a ClientClosedError.

See also

aclose() method.

Returns:

the client state.

Return type:

bool

abstractmethod async aclose() None

Close the client.

Once that happens, all future operations on the client object will raise a ClientClosedError. The remote end will receive no more data (after queued data is flushed).

Warning

aclose() performs a graceful close, waiting for the connection to close.

If aclose() is cancelled, the client is closed abruptly.

Can be safely called multiple times.

abstractmethod async send_packet(packet: _T_SentPacket) None

Sends packet to the remote endpoint.

Warning

In the case of a cancellation, it is impossible to know if all the packet data has been sent. This would leave the connection in an inconsistent state.

Parameters:

packet (_T_SentPacket) – the Python object to send.

Raises:
  • ClientClosedError – the client object is closed.

  • ConnectionError – connection unexpectedly closed during operation. You should not attempt any further operation and close the client object.

  • OSError – unrelated OS error occurred. You should check OSError.errno.

abstractmethod async recv_packet() _T_ReceivedPacket

Waits for a new packet to arrive from the remote endpoint.

Raises:
Returns:

the received packet.

Return type:

_T_ReceivedPacket

iter_received_packets(*, timeout: float | None = 0) AsyncIterator[_T_ReceivedPacket]

Returns an asynchronous iterator that waits for a new packet to arrive from the remote endpoint.

If timeout is not None, the entire receive operation will take at most timeout seconds; it defaults to zero.

Important

The timeout is for the entire iterator:

async_iterator = client.iter_received_packets(timeout=10)

# Let's say that this call took 6 seconds...
first_packet = await anext(async_iterator)

# ...then this call has a maximum of 4 seconds, not 10.
second_packet = await anext(async_iterator)

The time taken outside the iterator object is not decremented to the timeout parameter.

Parameters:

timeout (float | None) – the allowed time (in seconds) for all the receive operations.

Yields:

the received packet.

Return type:

AsyncIterator[_T_ReceivedPacket]

abstractmethod backend() AsyncBackend
Returns:

The backend implementation linked to this client.

Return type:

AsyncBackend

class easynetwork.clients.abc.AbstractNetworkClient

Bases: Generic[_T_SentPacket, _T_ReceivedPacket]

The base class for a network client interface.

abstractmethod is_closed() bool

Checks if the client is in a closed state.

If True, all future operations on the client object will raise a ClientClosedError.

See also

close() method.

Returns:

the client state.

Return type:

bool

abstractmethod close() None

Close the client.

Once that happens, all future operations on the client object will raise a ClientClosedError. The remote end will receive no more data (after queued data is flushed).

Can be safely called multiple times.

abstractmethod send_packet(packet: _T_SentPacket, *, timeout: float | None = ...) None

Sends packet to the remote endpoint.

If timeout is not None, the entire send operation will take at most timeout seconds.

Warning

A timeout on a send operation is unusual unless the implementation is using a lower-level communication protocol (such as SSL/TLS).

In the case of a timeout, it is impossible to know if all the packet data has been sent. This would leave the connection in an inconsistent state.

Parameters:
  • packet (_T_SentPacket) – the Python object to send.

  • timeout (float | None) – the allowed time (in seconds) for blocking operations.

Raises:
  • ClientClosedError – the client object is closed.

  • ConnectionError – connection unexpectedly closed during operation. You should not attempt any further operation and close the client object.

  • TimeoutError – the send operation does not end up after timeout seconds.

  • OSError – unrelated OS error occurred. You should check OSError.errno.

abstractmethod recv_packet(*, timeout: float | None = ...) _T_ReceivedPacket

Waits for a new packet to arrive from the remote endpoint.

If timeout is not None, the entire receive operation will take at most timeout seconds.

Parameters:

timeout (float | None) – the allowed time (in seconds) for blocking operations.

Raises:
Returns:

the received packet.

Return type:

_T_ReceivedPacket

iter_received_packets(*, timeout: float | None = 0) Iterator[_T_ReceivedPacket]

Returns an iterator that waits for a new packet to arrive from the remote endpoint.

If timeout is not None, the entire receive operation will take at most timeout seconds; it defaults to zero.

Important

The timeout is for the entire iterator:

iterator = client.iter_received_packets(timeout=10)

# Let's say that this call took 6 seconds...
first_packet = next(iterator)

# ...then this call has a maximum of 4 seconds, not 10.
second_packet = next(iterator)

The time taken outside the iterator object is not decremented to the timeout parameter.

Parameters:

timeout (float | None) – the allowed time (in seconds) for all the receive operations.

Yields:

the received packet.

Return type:

Iterator[_T_ReceivedPacket]

abstractmethod fileno() int

Returns the client’s file descriptor, or -1 if client is closed.

Returns:

the opened file descriptor.

Return type:

int

Asynchronous Client Objects (async def)

TCP Implementation

Asynchronous TCP Network client implementation module.

class easynetwork.clients.async_tcp.AsyncTCPNetworkClient

Bases: AbstractAsyncNetworkClient[_T_SentPacket, _T_ReceivedPacket]

An asynchronous network client interface for TCP connections.

__init__(address: tuple[str, int], /, protocol: StreamProtocol[_T_SentPacket, _T_ReceivedPacket] | BufferedStreamProtocol[_T_SentPacket, _T_ReceivedPacket, Any], backend: AsyncBackend | Literal['asyncio', 'trio'] | None = None, *, local_address: tuple[str, int] | None = ..., happy_eyeballs_delay: float | None = ..., ssl: SSLContext | bool | None = None, server_hostname: str | None = None, ssl_handshake_timeout: float | None = None, ssl_shutdown_timeout: float | None = None, ssl_standard_compatible: bool | None = None, max_recv_size: int | None = None) None
__init__(socket: socket, /, protocol: StreamProtocol[_T_SentPacket, _T_ReceivedPacket] | BufferedStreamProtocol[_T_SentPacket, _T_ReceivedPacket, Any], backend: AsyncBackend | Literal['asyncio', 'trio'] | None = None, *, ssl: SSLContext | bool | None = None, server_hostname: str | None = None, ssl_handshake_timeout: float | None = None, ssl_shutdown_timeout: float | None = None, ssl_standard_compatible: bool | None = None, max_recv_size: int | None = None) None
Common Parameters:
Connection Parameters:
  • address – A pair of (host, port) for connection.

  • happy_eyeballs_delay – the “Connection Attempt Delay” as defined in RFC 8305. A sensible default value recommended by the RFC is 0.25 (250 milliseconds).

  • local_address – If given, is a (local_host, local_port) tuple used to bind the socket locally.

Socket Parameters:

socket – An already connected TCP socket.socket. If socket is given, none of happy_eyeballs_delay and local_address should be specified.

Keyword Arguments:
  • ssl – If given and not false, a SSL/TLS transport is created (by default a plain TCP transport is created). If ssl is a ssl.SSLContext object, this context is used to create the transport; if ssl is True, a default context returned from ssl.create_default_context() is used.

  • server_hostname – sets or overrides the hostname that the target server’s certificate will be matched against. Should only be passed if ssl is not None. By default the value of the host in address argument is used. If socket is provided instead, there is no default and you must pass a value for server_hostname. If server_hostname is an empty string, hostname matching is disabled (which is a serious security risk, allowing for potential man-in-the-middle attacks).

  • ssl_handshake_timeout – (for a TLS connection) the time in seconds to wait for the TLS handshake to complete before aborting the connection. 60.0 seconds if None (default).

  • ssl_shutdown_timeout – the time in seconds to wait for the SSL shutdown to complete before aborting the connection. 30.0 seconds if None (default).

  • ssl_standard_compatible – if False, skip the closing handshake when closing the connection, and don’t raise an exception if the peer does the same.

  • max_recv_size – Read buffer size. If not given, a default reasonable value is used.

is_connected() bool

Checks if the client initialization is finished.

See also

wait_connected() method.

Returns:

the client connection state.

Return type:

bool

async wait_connected() None

Finishes initializing the client, doing the asynchronous operations that could not be done in the constructor. Does not require task synchronization.

It is not needed to call it directly if the client is used as an asynchronous context manager:

async with client:  # wait_connected() has been called.
    ...

Can be safely called multiple times.

Warning

Due to limitations of the underlying operating system APIs, it is not always possible to properly cancel a connection attempt once it has begun.

If wait_connected() is cancelled, and is unable to abort the connection attempt, then it will forcibly close the socket to prevent accidental re-use.

Raises:
is_closing() bool

Checks if the client is closed or in the process of being closed.

If True, all future operations on the client object will raise a ClientClosedError.

See also

aclose() method.

Returns:

the client state.

Return type:

bool

async aclose() None

Closes the client. Does not require task synchronization.

Once that happens, all future operations on the client object will raise a ClientClosedError. The remote end will receive no more data (after queued data is flushed).

Warning

aclose() performs a graceful close, waiting for the connection to close.

If aclose() is cancelled, the client is closed abruptly.

Can be safely called multiple times.

async send_packet(packet: _T_SentPacket) None

Sends packet to the remote endpoint. Does not require task synchronization.

Warning

In the case of a cancellation, it is impossible to know if all the packet data has been sent. This would leave the connection in an inconsistent state.

Parameters:

packet (_T_SentPacket) – the Python object to send.

Raises:
async send_eof() None

Closes the write end of the stream after the buffered write data is flushed. Does not require task synchronization.

Can be safely called multiple times.

Raises:

OSError – unrelated OS error occurred. You should check OSError.errno.

async recv_packet() _T_ReceivedPacket

Waits for a new packet to arrive from the remote endpoint. Does not require task synchronization.

Raises:
Returns:

the received packet.

Return type:

_T_ReceivedPacket

get_local_address() IPv4SocketAddress | IPv6SocketAddress

Returns the local socket IP address.

If wait_connected() was not called, an OSError may occur.

Raises:
Returns:

the client’s local address.

Return type:

IPv4SocketAddress | IPv6SocketAddress

get_remote_address() IPv4SocketAddress | IPv6SocketAddress

Returns the remote socket IP address.

If wait_connected() was not called, an OSError may occur.

Raises:
Returns:

the client’s remote address.

Return type:

IPv4SocketAddress | IPv6SocketAddress

backend() AsyncBackend
Returns:

The backend implementation linked to this client.

Return type:

AsyncBackend

iter_received_packets(*, timeout: float | None = 0) AsyncIterator[_T_ReceivedPacket]

Returns an asynchronous iterator that waits for a new packet to arrive from the remote endpoint.

If timeout is not None, the entire receive operation will take at most timeout seconds; it defaults to zero.

Important

The timeout is for the entire iterator:

async_iterator = client.iter_received_packets(timeout=10)

# Let's say that this call took 6 seconds...
first_packet = await anext(async_iterator)

# ...then this call has a maximum of 4 seconds, not 10.
second_packet = await anext(async_iterator)

The time taken outside the iterator object is not decremented to the timeout parameter.

Parameters:

timeout (float | None) – the allowed time (in seconds) for all the receive operations.

Yields:

the received packet.

Return type:

AsyncIterator[_T_ReceivedPacket]

property socket: SocketProxy

A view to the underlying socket instance. Read-only attribute.

May raise AttributeError if wait_connected() was not called.

UDP Implementation

Asynchronous UDP Network client implementation module.

class easynetwork.clients.async_udp.AsyncUDPNetworkClient

Bases: AbstractAsyncNetworkClient[_T_SentPacket, _T_ReceivedPacket]

An asynchronous network client interface for UDP communication.

__init__(address: tuple[str, int], /, protocol: DatagramProtocol[_T_SentPacket, _T_ReceivedPacket], backend: AsyncBackend | Literal['asyncio', 'trio'] | None = None, *, local_address: tuple[str, int] | None = ..., family: int = ...) None
__init__(socket: socket, /, protocol: DatagramProtocol[_T_SentPacket, _T_ReceivedPacket], backend: AsyncBackend | Literal['asyncio', 'trio'] | None = None) None
Common Parameters:
Connection Parameters:
  • address – A pair of (host, port) for connection.

  • local_address – If given, is a (local_host, local_port) tuple used to bind the socket locally.

  • family – The address family. Should be any of AF_UNSPEC, AF_INET or AF_INET6.

Socket Parameters:

socket – An already connected UDP socket.socket. If socket is given, none of family and local_address should be specified.

is_connected() bool

Checks if the client initialization is finished.

See also

wait_connected() method.

Returns:

the client connection state.

Return type:

bool

async wait_connected() None

Finishes initializing the client, doing the asynchronous operations that could not be done in the constructor. Does not require task synchronization.

It is not needed to call it directly if the client is used as an asynchronous context manager:

async with client:  # wait_connected() has been called.
    ...

Can be safely called multiple times.

Raises:
is_closing() bool

Checks if the client is closed or in the process of being closed.

If True, all future operations on the client object will raise a ClientClosedError.

See also

aclose() method.

Returns:

the client state.

Return type:

bool

async aclose() None

Closes the client. Does not require task synchronization.

Once that happens, all future operations on the client object will raise a ClientClosedError. The remote end will receive no more data (after queued data is flushed).

Warning

aclose() performs a graceful close, waiting for the connection to close.

If aclose() is cancelled, the client is closed abruptly.

Can be safely called multiple times.

async send_packet(packet: _T_SentPacket) None

Sends packet to the remote endpoint. Does not require task synchronization.

Warning

In the case of a cancellation, it is impossible to know if all the packet data has been sent.

Parameters:

packet (_T_SentPacket) – the Python object to send.

Raises:
async recv_packet() _T_ReceivedPacket

Waits for a new packet to arrive from the remote endpoint. Does not require task synchronization.

Raises:
Returns:

the received packet.

Return type:

_T_ReceivedPacket

get_local_address() IPv4SocketAddress | IPv6SocketAddress

Returns the local socket IP address.

If wait_connected() was not called, an OSError may occur.

Raises:
Returns:

the client’s local address.

Return type:

IPv4SocketAddress | IPv6SocketAddress

get_remote_address() IPv4SocketAddress | IPv6SocketAddress

Returns the remote socket IP address.

If wait_connected() was not called, an OSError may occur.

Raises:
Returns:

the client’s remote address.

Return type:

IPv4SocketAddress | IPv6SocketAddress

backend() AsyncBackend
Returns:

The backend implementation linked to this client.

Return type:

AsyncBackend

iter_received_packets(*, timeout: float | None = 0) AsyncIterator[_T_ReceivedPacket]

Returns an asynchronous iterator that waits for a new packet to arrive from the remote endpoint.

If timeout is not None, the entire receive operation will take at most timeout seconds; it defaults to zero.

Important

The timeout is for the entire iterator:

async_iterator = client.iter_received_packets(timeout=10)

# Let's say that this call took 6 seconds...
first_packet = await anext(async_iterator)

# ...then this call has a maximum of 4 seconds, not 10.
second_packet = await anext(async_iterator)

The time taken outside the iterator object is not decremented to the timeout parameter.

Parameters:

timeout (float | None) – the allowed time (in seconds) for all the receive operations.

Yields:

the received packet.

Return type:

AsyncIterator[_T_ReceivedPacket]

property socket: SocketProxy

A view to the underlying socket instance. Read-only attribute.

May raise AttributeError if wait_connected() was not called.

UNIX Stream Implementation

Asynchronous Unix stream client implementation module.

Added in version 1.1.

class easynetwork.clients.async_unix_stream.AsyncUnixStreamClient

Bases: AbstractAsyncNetworkClient[_T_SentPacket, _T_ReceivedPacket]

An asynchronous Unix stream client.

Added in version 1.1.

__init__(path: str | PathLike[str] | bytes | UnixSocketAddress, /, protocol: StreamProtocol[_T_SentPacket, _T_ReceivedPacket] | BufferedStreamProtocol[_T_SentPacket, _T_ReceivedPacket, Any], backend: AsyncBackend | Literal['asyncio', 'trio'] | None = None, *, local_path: str | PathLike[str] | bytes | UnixSocketAddress | None = ..., max_recv_size: int | None = None) None
__init__(socket: socket, /, protocol: StreamProtocol[_T_SentPacket, _T_ReceivedPacket] | BufferedStreamProtocol[_T_SentPacket, _T_ReceivedPacket, Any], backend: AsyncBackend | Literal['asyncio', 'trio'] | None = None, *, max_recv_size: int | None = None) None
Common Parameters:
Connection Parameters:
  • path – Path of the socket.

  • local_path – If given, is a Unix socket address used to bind the socket locally. If local_path points to a filepath, it will not be deleted on client close.

Socket Parameters:

socket – An already connected Unix socket.socket. If socket is given, local_path should not be specified.

Keyword Arguments:

max_recv_size – Read buffer size. If not given, a default reasonable value is used.

is_connected() bool

Checks if the client initialization is finished.

See also

wait_connected() method.

Returns:

the client connection state.

Return type:

bool

async wait_connected() None

Finishes initializing the client, doing the asynchronous operations that could not be done in the constructor. Does not require task synchronization.

It is not needed to call it directly if the client is used as an asynchronous context manager:

async with client:  # wait_connected() has been called.
    ...

Can be safely called multiple times.

Warning

Due to limitations of the underlying operating system APIs, it is not always possible to properly cancel a connection attempt once it has begun.

If wait_connected() is cancelled, and is unable to abort the connection attempt, then it will forcibly close the socket to prevent accidental re-use.

Raises:
is_closing() bool

Checks if the client is closed or in the process of being closed.

If True, all future operations on the client object will raise a ClientClosedError.

See also

aclose() method.

Returns:

the client state.

Return type:

bool

async aclose() None

Closes the client. Does not require task synchronization.

Once that happens, all future operations on the client object will raise a ClientClosedError. The remote end will receive no more data (after queued data is flushed).

Warning

aclose() performs a graceful close, waiting for the connection to close.

If aclose() is cancelled, the client is closed abruptly.

Can be safely called multiple times.

async send_packet(packet: _T_SentPacket, *, ancillary_data: SocketAncillary | None = None) None

Sends packet to the remote endpoint. Does not require task synchronization.

Changed in version 1.2: Added ancillary_data parameter.

Warning

In the case of a cancellation, it is impossible to know if all the packet data has been sent. This would leave the connection in an inconsistent state.

Parameters:
  • packet (_T_SentPacket) – the Python object to send.

  • ancillary_data (SocketAncillary | None) – the socket ancillary data to send along with the packet.

Raises:
async send_eof() None

Closes the write end of the stream after the buffered write data is flushed. Does not require task synchronization.

Can be safely called multiple times.

Raises:

OSError – unrelated OS error occurred. You should check OSError.errno.

async recv_packet(*, ancillary_data: SocketAncillary | None = None, ancillary_bufsize: int | None = None) _T_ReceivedPacket

Waits for a new packet to arrive from the remote endpoint. Does not require task synchronization.

Changed in version 1.2: Added ancillary_data and ancillary_bufsize parameters.

Parameters:
  • ancillary_data (SocketAncillary | None) – where to write received ancillary data.

  • ancillary_bufsize (int | None) – read buffer size for ancillary data. Defaults to ~8KiB.

Raises:
Returns:

the received packet.

Return type:

_T_ReceivedPacket

get_local_name() UnixSocketAddress

Returns the socket name.

If wait_connected() was not called, an OSError may occur.

Raises:
Returns:

the client’s local name.

Return type:

UnixSocketAddress

get_peer_name() UnixSocketAddress

Returns the peer socket name.

If wait_connected() was not called, an OSError may occur.

Raises:
Returns:

the client’s peer name.

Return type:

UnixSocketAddress

get_peer_credentials() UnixCredentials

Returns the credentials of the peer process connected to this socket.

If wait_connected() was not called, an OSError may occur.

Raises:
Return type:

UnixCredentials

backend() AsyncBackend
Returns:

The backend implementation linked to this client.

Return type:

AsyncBackend

iter_received_packets(*, timeout: float | None = 0) AsyncIterator[_T_ReceivedPacket]

Returns an asynchronous iterator that waits for a new packet to arrive from the remote endpoint.

If timeout is not None, the entire receive operation will take at most timeout seconds; it defaults to zero.

Important

The timeout is for the entire iterator:

async_iterator = client.iter_received_packets(timeout=10)

# Let's say that this call took 6 seconds...
first_packet = await anext(async_iterator)

# ...then this call has a maximum of 4 seconds, not 10.
second_packet = await anext(async_iterator)

The time taken outside the iterator object is not decremented to the timeout parameter.

Parameters:

timeout (float | None) – the allowed time (in seconds) for all the receive operations.

Yields:

the received packet.

Return type:

AsyncIterator[_T_ReceivedPacket]

property socket: SocketProxy

A view to the underlying socket instance. Read-only attribute.

May raise AttributeError if wait_connected() was not called.

UNIX Datagram Implementation

Asynchronous Unix datagram client implementation module.

Added in version 1.1.

class easynetwork.clients.async_unix_datagram.AsyncUnixDatagramClient

Bases: AbstractAsyncNetworkClient[_T_SentPacket, _T_ReceivedPacket]

An asynchronous Unix datagram client.

Added in version 1.1.

__init__(path: str | PathLike[str] | bytes | UnixSocketAddress, /, protocol: DatagramProtocol[_T_SentPacket, _T_ReceivedPacket], backend: AsyncBackend | Literal['asyncio', 'trio'] | None = None, *, local_path: str | PathLike[str] | bytes | UnixSocketAddress | None = ...) None
__init__(socket: socket, /, protocol: DatagramProtocol[_T_SentPacket, _T_ReceivedPacket], backend: AsyncBackend | Literal['asyncio', 'trio'] | None = None) None
Common Parameters:
Connection Parameters:
  • path – Path of the socket.

  • local_path – If given, is a Unix socket address used to bind the socket locally.

Socket Parameters:

socket – An already connected Unix datagram socket.socket. If socket is given, local_address should not be specified.

is_connected() bool

Checks if the client initialization is finished.

See also

wait_connected() method.

Returns:

the client connection state.

Return type:

bool

async wait_connected() None

Finishes initializing the client, doing the asynchronous operations that could not be done in the constructor. Does not require task synchronization.

It is not needed to call it directly if the client is used as an asynchronous context manager:

async with client:  # wait_connected() has been called.
    ...

Can be safely called multiple times.

Raises:
is_closing() bool

Checks if the client is closed or in the process of being closed.

If True, all future operations on the client object will raise a ClientClosedError.

See also

aclose() method.

Returns:

the client state.

Return type:

bool

async aclose() None

Closes the client. Does not require task synchronization.

Once that happens, all future operations on the client object will raise a ClientClosedError. The remote end will receive no more data (after queued data is flushed).

Warning

aclose() performs a graceful close, waiting for the connection to close.

If aclose() is cancelled, the client is closed abruptly.

Can be safely called multiple times.

async send_packet(packet: _T_SentPacket, *, ancillary_data: SocketAncillary | None = None) None

Sends packet to the remote endpoint. Does not require task synchronization.

Changed in version 1.2: Added ancillary_data parameter.

Warning

In the case of a cancellation, it is impossible to know if all the packet data has been sent.

Parameters:
  • packet (_T_SentPacket) – the Python object to send.

  • ancillary_data (SocketAncillary | None) – the socket ancillary data to send along with the packet.

Raises:
async recv_packet(*, ancillary_data: SocketAncillary | None = None, ancillary_bufsize: int | None = None) _T_ReceivedPacket

Waits for a new packet to arrive from the remote endpoint. Does not require task synchronization.

Changed in version 1.2: Added ancillary_data and ancillary_bufsize parameters.

Parameters:
  • ancillary_data (SocketAncillary | None) – where to write received ancillary data.

  • ancillary_bufsize (int | None) – read buffer size for ancillary data. Defaults to ~8KiB.

Raises:
Returns:

the received packet.

Return type:

_T_ReceivedPacket

get_local_name() UnixSocketAddress

Returns the socket name.

If wait_connected() was not called, an OSError may occur.

Raises:
Returns:

the client’s local name.

Return type:

UnixSocketAddress

get_peer_name() UnixSocketAddress

Returns the peer socket name.

If wait_connected() was not called, an OSError may occur.

Raises:
Returns:

the client’s peer name.

Return type:

UnixSocketAddress

backend() AsyncBackend
Returns:

The backend implementation linked to this client.

Return type:

AsyncBackend

iter_received_packets(*, timeout: float | None = 0) AsyncIterator[_T_ReceivedPacket]

Returns an asynchronous iterator that waits for a new packet to arrive from the remote endpoint.

If timeout is not None, the entire receive operation will take at most timeout seconds; it defaults to zero.

Important

The timeout is for the entire iterator:

async_iterator = client.iter_received_packets(timeout=10)

# Let's say that this call took 6 seconds...
first_packet = await anext(async_iterator)

# ...then this call has a maximum of 4 seconds, not 10.
second_packet = await anext(async_iterator)

The time taken outside the iterator object is not decremented to the timeout parameter.

Parameters:

timeout (float | None) – the allowed time (in seconds) for all the receive operations.

Yields:

the received packet.

Return type:

AsyncIterator[_T_ReceivedPacket]

property socket: SocketProxy

A view to the underlying socket instance. Read-only attribute.

May raise AttributeError if wait_connected() was not called.

Synchronous Client Objects

TCP Implementation

TCP Network client implementation module.

class easynetwork.clients.tcp.TCPNetworkClient

Bases: AbstractNetworkClient[_T_SentPacket, _T_ReceivedPacket]

A network client interface for TCP connections.

__init__(address: tuple[str, int], /, protocol: StreamProtocol[_T_SentPacket, _T_ReceivedPacket] | BufferedStreamProtocol[_T_SentPacket, _T_ReceivedPacket, Any], *, connect_timeout: float | None = ..., local_address: tuple[str, int] | None = ..., ssl: SSLContext | bool | None = None, server_hostname: str | None = None, ssl_handshake_timeout: float | None = None, ssl_shutdown_timeout: float | None = None, ssl_standard_compatible: bool | None = None, max_recv_size: int | None = None, retry_interval: float = 1.0) None
__init__(socket: socket, /, protocol: StreamProtocol[_T_SentPacket, _T_ReceivedPacket] | BufferedStreamProtocol[_T_SentPacket, _T_ReceivedPacket, Any], *, ssl: SSLContext | bool | None = None, server_hostname: str | None = None, ssl_handshake_timeout: float | None = None, ssl_shutdown_timeout: float | None = None, ssl_standard_compatible: bool | None = None, max_recv_size: int | None = None, retry_interval: float = 1.0) None
Common Parameters:

protocol – The protocol object to use.

Connection Parameters:
  • address – A pair of (host, port) for connection.

  • connect_timeout – The connection timeout (in seconds).

  • local_address – If given, is a (local_host, local_port) tuple used to bind the socket locally.

Socket Parameters:

socket – An already connected TCP socket.socket. If socket is given, none of connect_timeout and local_address should be specified.

Keyword Arguments:
  • ssl – If given and not false, a SSL/TLS transport is created (by default a plain TCP transport is created). If ssl is a ssl.SSLContext object, this context is used to create the transport; if ssl is True, a default context returned from ssl.create_default_context() is used.

  • server_hostname – sets or overrides the hostname that the target server’s certificate will be matched against. Should only be passed if ssl is not None. By default the value of the host in address argument is used. If socket is provided instead, there is no default and you must pass a value for server_hostname. If server_hostname is an empty string, hostname matching is disabled (which is a serious security risk, allowing for potential man-in-the-middle attacks).

  • ssl_handshake_timeout – (for a TLS connection) the time in seconds to wait for the TLS handshake to complete before aborting the connection. 60.0 seconds if None (default).

  • ssl_shutdown_timeout – the time in seconds to wait for the SSL shutdown to complete before aborting the connection. 30.0 seconds if None (default).

  • ssl_standard_compatible – if False, skip the closing handshake when closing the connection, and don’t raise an exception if the peer does the same.

  • max_recv_size – Read buffer size. If not given, a default reasonable value is used.

  • retry_interval – The maximum wait time to wait for a blocking operation before retrying. Set it to math.inf to disable this feature.

is_closed() bool

Checks if the client is in a closed state. Thread-safe.

If True, all future operations on the client object will raise a ClientClosedError.

Returns:

the client state.

Return type:

bool

close() None

Close the client. Thread-safe.

Once that happens, all future operations on the client object will raise a ClientClosedError. The remote end will receive no more data (after queued data is flushed).

Can be safely called multiple times.

send_packet(packet: _T_SentPacket, *, timeout: float | None = None) None

Sends packet to the remote endpoint. Thread-safe.

If timeout is not None, the entire send operation will take at most timeout seconds.

Warning

A timeout on a send operation is unusual unless you have a SSL/TLS context.

In the case of a timeout, it is impossible to know if all the packet data has been sent. This would leave the connection in an inconsistent state.

Important

The lock acquisition time is included in the timeout.

This means that you may get a TimeoutError because it took too long to get the lock.

Parameters:
  • packet (_T_SentPacket) – the Python object to send.

  • timeout (float | None) – the allowed time (in seconds) for blocking operations.

Raises:
send_eof() None

Close the write end of the stream after the buffered write data is flushed. Thread-safe.

This method does nothing if the client is closed.

Can be safely called multiple times.

Raises:

OSError – unrelated OS error occurred. You should check OSError.errno.

recv_packet(*, timeout: float | None = None) _T_ReceivedPacket

Waits for a new packet to arrive from the remote endpoint. Thread-safe.

If timeout is not None, the entire receive operation will take at most timeout seconds.

Important

The lock acquisition time is included in the timeout.

This means that you may get a TimeoutError because it took too long to get the lock.

Parameters:

timeout (float | None) – the allowed time (in seconds) for blocking operations.

Raises:
Returns:

the received packet.

Return type:

_T_ReceivedPacket

get_local_address() IPv4SocketAddress | IPv6SocketAddress

Returns the local socket IP address. Thread-safe.

Raises:
Returns:

the client’s local address.

Return type:

IPv4SocketAddress | IPv6SocketAddress

get_remote_address() IPv4SocketAddress | IPv6SocketAddress

Returns the remote socket IP address. Thread-safe.

Raises:
Returns:

the client’s remote address.

Return type:

IPv4SocketAddress | IPv6SocketAddress

fileno() int

Returns the socket’s file descriptor, or -1 if the client (or the socket) is closed. Thread-safe.

Returns:

the opened file descriptor.

Return type:

int

iter_received_packets(*, timeout: float | None = 0) Iterator[_T_ReceivedPacket]

Returns an iterator that waits for a new packet to arrive from the remote endpoint.

If timeout is not None, the entire receive operation will take at most timeout seconds; it defaults to zero.

Important

The timeout is for the entire iterator:

iterator = client.iter_received_packets(timeout=10)

# Let's say that this call took 6 seconds...
first_packet = next(iterator)

# ...then this call has a maximum of 4 seconds, not 10.
second_packet = next(iterator)

The time taken outside the iterator object is not decremented to the timeout parameter.

Parameters:

timeout (float | None) – the allowed time (in seconds) for all the receive operations.

Yields:

the received packet.

Return type:

Iterator[_T_ReceivedPacket]

property socket: SocketProxy

A view to the underlying socket instance. Read-only attribute.

UDP Implementation

UDP Network client implementation module.

class easynetwork.clients.udp.UDPNetworkClient

Bases: AbstractNetworkClient[_T_SentPacket, _T_ReceivedPacket]

A network client interface for UDP communication.

__init__(address: tuple[str, int], /, protocol: DatagramProtocol[_T_SentPacket, _T_ReceivedPacket], *, local_address: tuple[str, int] | None = ..., family: int = ..., retry_interval: float = 1.0) None
__init__(socket: socket, /, protocol: DatagramProtocol[_T_SentPacket, _T_ReceivedPacket], *, retry_interval: float = 1.0) None
Common Parameters:

protocol – The protocol object to use.

Connection Parameters:
  • address – A pair of (host, port) for connection.

  • local_address – If given, is a (local_host, local_port) tuple used to bind the socket locally.

  • family – The address family. Should be any of AF_UNSPEC, AF_INET or AF_INET6.

Socket Parameters:

socket – An already connected UDP socket.socket. If socket is given, none of family and local_address should be specified.

Keyword Arguments:

retry_interval – The maximum wait time to wait for a blocking operation before retrying. Set it to math.inf to disable this feature.

is_closed() bool

Checks if the client is in a closed state. Thread-safe.

If True, all future operations on the client object will raise a ClientClosedError.

Returns:

the client state.

Return type:

bool

close() None

Close the client. Thread-safe.

Once that happens, all future operations on the client object will raise a ClientClosedError. The remote end will receive no more data (after queued data is flushed).

Can be safely called multiple times.

get_local_address() IPv4SocketAddress | IPv6SocketAddress

Returns the local socket IP address. Thread-safe.

Raises:
Returns:

the client’s local address.

Return type:

IPv4SocketAddress | IPv6SocketAddress

get_remote_address() IPv4SocketAddress | IPv6SocketAddress

Returns the remote socket IP address. Thread-safe.

Raises:
Returns:

the client’s remote address.

Return type:

IPv4SocketAddress | IPv6SocketAddress

send_packet(packet: _T_SentPacket, *, timeout: float | None = None) None

Sends packet to the remote endpoint. Thread-safe.

If timeout is not None, the entire send operation will take at most timeout seconds.

Warning

A timeout on a send operation is unusual.

In the case of a timeout, it is impossible to know if all the packet data has been sent.

Important

The lock acquisition time is included in the timeout.

This means that you may get a TimeoutError because it took too long to get the lock.

Parameters:
  • packet (_T_SentPacket) – the Python object to send.

  • timeout (float | None) – the allowed time (in seconds) for blocking operations.

Raises:
recv_packet(*, timeout: float | None = None) _T_ReceivedPacket

Waits for a new packet from the remote endpoint. Thread-safe.

If timeout is not None, the entire receive operation will take at most timeout seconds.

Important

The lock acquisition time is included in the timeout.

This means that you may get a TimeoutError because it took too long to get the lock.

Parameters:

timeout (float | None) – the allowed time (in seconds) for blocking operations.

Raises:
Returns:

the received packet.

Return type:

_T_ReceivedPacket

fileno() int

Returns the socket’s file descriptor, or -1 if the client (or the socket) is closed. Thread-safe.

Returns:

the opened file descriptor.

Return type:

int

iter_received_packets(*, timeout: float | None = 0) Iterator[_T_ReceivedPacket]

Returns an iterator that waits for a new packet to arrive from the remote endpoint.

If timeout is not None, the entire receive operation will take at most timeout seconds; it defaults to zero.

Important

The timeout is for the entire iterator:

iterator = client.iter_received_packets(timeout=10)

# Let's say that this call took 6 seconds...
first_packet = next(iterator)

# ...then this call has a maximum of 4 seconds, not 10.
second_packet = next(iterator)

The time taken outside the iterator object is not decremented to the timeout parameter.

Parameters:

timeout (float | None) – the allowed time (in seconds) for all the receive operations.

Yields:

the received packet.

Return type:

Iterator[_T_ReceivedPacket]

property socket: SocketProxy

A view to the underlying socket instance. Read-only attribute.

UNIX Stream Implementation

Unix stream client implementation module.

Added in version 1.1.

class easynetwork.clients.unix_stream.UnixStreamClient

Bases: AbstractNetworkClient[_T_SentPacket, _T_ReceivedPacket]

A Unix stream client.

Added in version 1.1.

__init__(path: str | PathLike[str] | bytes | UnixSocketAddress, /, protocol: StreamProtocol[_T_SentPacket, _T_ReceivedPacket] | BufferedStreamProtocol[_T_SentPacket, _T_ReceivedPacket, Any], *, connect_timeout: float | None = ..., local_path: str | PathLike[str] | bytes | UnixSocketAddress | None = ..., max_recv_size: int | None = None, retry_interval: float = 1.0) None
__init__(socket: socket, /, protocol: StreamProtocol[_T_SentPacket, _T_ReceivedPacket] | BufferedStreamProtocol[_T_SentPacket, _T_ReceivedPacket, Any], *, max_recv_size: int | None = None, retry_interval: float = 1.0) None
Common Parameters:

protocol – The protocol object to use.

Connection Parameters:
  • path – Path of the socket.

  • connect_timeout – The connection timeout (in seconds).

  • local_path – If given, is a Unix socket address used to bind the socket locally. If local_path points to a filepath, it will not be deleted on client close.

Socket Parameters:

socket – An already connected Unix socket.socket. If socket is given, none of connect_timeout and local_path should be specified.

Keyword Arguments:
  • max_recv_size – Read buffer size. If not given, a default reasonable value is used.

  • retry_interval – The maximum wait time to wait for a blocking operation before retrying. Set it to math.inf to disable this feature.

is_closed() bool

Checks if the client is in a closed state. Thread-safe.

If True, all future operations on the client object will raise a ClientClosedError.

Returns:

the client state.

Return type:

bool

close() None

Close the client. Thread-safe.

Once that happens, all future operations on the client object will raise a ClientClosedError. The remote end will receive no more data (after queued data is flushed).

Can be safely called multiple times.

send_packet(packet: _T_SentPacket, *, ancillary_data: SocketAncillary | None = None, timeout: float | None = None) None

Sends packet to the remote endpoint. Thread-safe.

If timeout is not None, the entire send operation will take at most timeout seconds.

Changed in version 1.2: Added ancillary_data parameter.

Warning

A timeout on a send operation is unusual.

In the case of a timeout, it is impossible to know if all the packet data has been sent. This would leave the connection in an inconsistent state.

Important

The lock acquisition time is included in the timeout.

This means that you may get a TimeoutError because it took too long to get the lock.

Parameters:
  • packet (_T_SentPacket) – the Python object to send.

  • ancillary_data (SocketAncillary | None) – the socket ancillary data to send along with the packet.

  • timeout (float | None) – the allowed time (in seconds) for blocking operations.

Raises:
send_eof() None

Close the write end of the stream after the buffered write data is flushed. Thread-safe.

This method does nothing if the client is closed.

Can be safely called multiple times.

Raises:

OSError – unrelated OS error occurred. You should check OSError.errno.

recv_packet(*, ancillary_data: SocketAncillary | None = None, ancillary_bufsize: int | None = None, timeout: float | None = None) _T_ReceivedPacket

Waits for a new packet to arrive from the remote endpoint. Thread-safe.

If timeout is not None, the entire receive operation will take at most timeout seconds.

Changed in version 1.2: Added ancillary_data and ancillary_bufsize parameters.

Important

The lock acquisition time is included in the timeout.

This means that you may get a TimeoutError because it took too long to get the lock.

Parameters:
  • ancillary_data (SocketAncillary | None) – where to write received ancillary data.

  • ancillary_bufsize (int | None) – read buffer size for ancillary data.

  • timeout (float | None) – the allowed time (in seconds) for blocking operations.

Raises:
  • ClientClosedError – the client object is closed.

  • ConnectionError – connection unexpectedly closed during operation. You should not attempt any further operation and close the client object.

  • EOFError – could not deserialize packet because of partial chunk reception with ancillary data.

  • TimeoutError – the receive operation does not end up after timeout seconds.

  • OSError – unrelated OS error occurred. You should check OSError.errno.

  • StreamProtocolParseError – invalid data received.

Returns:

the received packet.

Return type:

_T_ReceivedPacket

get_local_name() UnixSocketAddress

Returns the socket name. Thread-safe.

Raises:
Returns:

the client’s local name.

Return type:

UnixSocketAddress

get_peer_name() UnixSocketAddress

Returns the peer socket name. Thread-safe.

Raises:
Returns:

the client’s peer name.

Return type:

UnixSocketAddress

get_peer_credentials() UnixCredentials

Returns the credentials of the peer process connected to this socket. Thread-safe.

Raises:
Return type:

UnixCredentials

fileno() int

Returns the socket’s file descriptor, or -1 if the client (or the socket) is closed. Thread-safe.

Returns:

the opened file descriptor.

Return type:

int

iter_received_packets(*, timeout: float | None = 0) Iterator[_T_ReceivedPacket]

Returns an iterator that waits for a new packet to arrive from the remote endpoint.

If timeout is not None, the entire receive operation will take at most timeout seconds; it defaults to zero.

Important

The timeout is for the entire iterator:

iterator = client.iter_received_packets(timeout=10)

# Let's say that this call took 6 seconds...
first_packet = next(iterator)

# ...then this call has a maximum of 4 seconds, not 10.
second_packet = next(iterator)

The time taken outside the iterator object is not decremented to the timeout parameter.

Parameters:

timeout (float | None) – the allowed time (in seconds) for all the receive operations.

Yields:

the received packet.

Return type:

Iterator[_T_ReceivedPacket]

property socket: SocketProxy

A view to the underlying socket instance. Read-only attribute.

UNIX Datagram Implementation

Unix datagram client implementation module.

Added in version 1.1.

class easynetwork.clients.unix_datagram.UnixDatagramClient

Bases: AbstractNetworkClient[_T_SentPacket, _T_ReceivedPacket]

A Unix datagram client.

Added in version 1.1.

__init__(path: str | PathLike[str] | bytes | UnixSocketAddress, /, protocol: DatagramProtocol[_T_SentPacket, _T_ReceivedPacket], *, local_path: str | PathLike[str] | bytes | UnixSocketAddress | None = ..., retry_interval: float = 1.0) None
__init__(socket: socket, /, protocol: DatagramProtocol[_T_SentPacket, _T_ReceivedPacket], *, retry_interval: float = 1.0) None
Common Parameters:

protocol – The protocol object to use.

Connection Parameters:
  • path – Path of the socket.

  • local_path – If given, is a Unix socket address used to bind the socket locally.

Socket Parameters:
  • socket – An already connected Unix datagram socket.socket. If socket is given,

  • `local_path` should not be specified.

Keyword Arguments:

retry_interval – The maximum wait time to wait for a blocking operation before retrying. Set it to math.inf to disable this feature.

is_closed() bool

Checks if the client is in a closed state. Thread-safe.

If True, all future operations on the client object will raise a ClientClosedError.

Returns:

the client state.

Return type:

bool

close() None

Close the client. Thread-safe.

Once that happens, all future operations on the client object will raise a ClientClosedError. The remote end will receive no more data (after queued data is flushed).

Can be safely called multiple times.

send_packet(packet: _T_SentPacket, *, ancillary_data: SocketAncillary | None = None, timeout: float | None = None) None

Sends packet to the remote endpoint. Thread-safe.

If timeout is not None, the entire send operation will take at most timeout seconds.

Changed in version 1.2: Added ancillary_data parameter.

Warning

A timeout on a send operation is unusual.

In the case of a timeout, it is impossible to know if all the packet data has been sent.

Important

The lock acquisition time is included in the timeout.

This means that you may get a TimeoutError because it took too long to get the lock.

Parameters:
  • packet (_T_SentPacket) – the Python object to send.

  • ancillary_data (SocketAncillary | None) – the socket ancillary data to send along with the packet.

  • timeout (float | None) – the allowed time (in seconds) for blocking operations.

Raises:
recv_packet(*, ancillary_data: SocketAncillary | None = None, ancillary_bufsize: int | None = None, timeout: float | None = None) _T_ReceivedPacket

Waits for a new packet from the remote endpoint. Thread-safe.

If timeout is not None, the entire receive operation will take at most timeout seconds.

Changed in version 1.2: Added ancillary_data and ancillary_bufsize parameters.

Important

The lock acquisition time is included in the timeout.

This means that you may get a TimeoutError because it took too long to get the lock.

Parameters:
  • ancillary_data (SocketAncillary | None) – where to write received ancillary data.

  • ancillary_bufsize (int | None) – read buffer size for ancillary data.

  • timeout (float | None) – the allowed time (in seconds) for blocking operations.

Raises:
Returns:

the received packet.

Return type:

_T_ReceivedPacket

get_local_name() UnixSocketAddress

Returns the socket name. Thread-safe.

Raises:
Returns:

the client’s local name.

Return type:

UnixSocketAddress

get_peer_name() UnixSocketAddress

Returns the peer socket name. Thread-safe.

Raises:
Returns:

the client’s peer name.

Return type:

UnixSocketAddress

fileno() int

Returns the socket’s file descriptor, or -1 if the client (or the socket) is closed. Thread-safe.

Returns:

the opened file descriptor.

Return type:

int

iter_received_packets(*, timeout: float | None = 0) Iterator[_T_ReceivedPacket]

Returns an iterator that waits for a new packet to arrive from the remote endpoint.

If timeout is not None, the entire receive operation will take at most timeout seconds; it defaults to zero.

Important

The timeout is for the entire iterator:

iterator = client.iter_received_packets(timeout=10)

# Let's say that this call took 6 seconds...
first_packet = next(iterator)

# ...then this call has a maximum of 4 seconds, not 10.
second_packet = next(iterator)

The time taken outside the iterator object is not decremented to the timeout parameter.

Parameters:

timeout (float | None) – the allowed time (in seconds) for all the receive operations.

Yields:

the received packet.

Return type:

Iterator[_T_ReceivedPacket]

property socket: SocketProxy

A view to the underlying socket instance. Read-only attribute.


See also

How-to — TCP Client Endpoints

Describes what can be done with the clients.

How-to — UDP Client Endpoints

Describes what can be done with the clients.

Alternative — Unix Stream Client Endpoints

Describes what can be done with the clients.

Alternative — Unix Datagram Client Endpoints

Describes what can be done with the clients.