embassy-net

Crates

git

Versions

default

Flavors

Skip to main content

TcpSocket

Struct TcpSocket 

Source
pub struct TcpSocket<'a, 'd> { /* private fields */ }
Expand description

A Transmission Control Protocol socket.

A TCP socket represents a single connection (connecting or connected): its 4-tuple is fully set from the start, by connect or by accept. Passive open lives in TcpListener.

'a is the lifetime of the socket’s buffers, 'd the lifetime of the stack.

Implementations§

Source§

impl<'a, 'd> TcpSocket<'a, 'd>

Source

pub fn new( stack: Stack<'d>, rx_buffer: &'a mut [u8], tx_buffer: &'a mut [u8], ) -> Result<Self, Full>

Create a new TCP socket on the given stack, with the given buffers.

§Errors
  • Full: if the stack has no room for another TCP socket. Only possible without the alloc feature, where the limit is set by the tcp-socket-count-N feature of xarxa.
Source

pub fn recv_capacity(&self) -> usize

Return the maximum number of bytes inside the recv buffer.

Source

pub fn send_capacity(&self) -> usize

Return the maximum number of bytes inside the transmit buffer.

Source

pub fn send_queue(&self) -> usize

Return the amount of octets queued in the transmit buffer.

Note that the Berkeley sockets interface does not have an equivalent of this API.

Source

pub fn recv_queue(&self) -> usize

Return the amount of octets queued in the receive buffer. This value can be larger than the slice read by the next recv or peek call because it includes all queued octets, and not only the octets that may be returned as a contiguous slice.

Note that the Berkeley sockets interface does not have an equivalent of this API.

Source

pub async fn write_with<R>( &mut self, f: impl FnOnce(&mut [u8]) -> (usize, R), ) -> Result<R, Error>

Call f with the largest contiguous slice of octets in the transmit buffer, and enqueue the amount of elements returned by f.

If the socket is not ready to accept data, it waits until it is.

Source

pub fn try_write_with<R>( &mut self, f: impl FnOnce(&mut [u8]) -> (usize, R), ) -> Result<R, TryError<Error>>

Call f with the largest contiguous slice of octets in the transmit buffer, and enqueue the amount of elements returned by f.

This method will not wait for the buffer to become free.

If the socket’s send buffer is full, this method will return Err(TryError::WouldBlock).

Source

pub async fn read_with<R>( &mut self, f: impl FnOnce(&mut [u8]) -> (usize, R), ) -> Result<R, Error>

Call f with the largest contiguous slice of octets in the receive buffer, and dequeue the amount of elements returned by f.

If no data is available, it waits until there is at least one byte available.

Source

pub fn try_read_with<R>( &mut self, f: impl FnOnce(&mut [u8]) -> (usize, R), ) -> Result<R, TryError<Error>>

Call f with the largest contiguous slice of octets in the receive buffer, and dequeue the amount of elements returned by f.

This method will not wait for data to be received.

If no data is available, this method will return Err(TryError::WouldBlock).

Source

pub async fn peek(&mut self, buf: &mut [u8]) -> Result<usize, Error>

Peek at received data without removing it from the receive buffer, copying it into buf.

If no data is available, it waits until there is at least one byte available.

Like read, a return value of Ok(0) means that all data has been read and the remote side has closed our receive half of the socket.

Source

pub fn try_peek(&mut self, buf: &mut [u8]) -> Result<usize, TryError<Error>>

Peek at received data without removing it from the receive buffer, copying it into buf.

This method will not wait for data to be received.

If no data is available, this method will return Err(TryError::WouldBlock).

Source

pub async fn peek_with<R>( &mut self, f: impl FnOnce(&[u8]) -> R, ) -> Result<R, Error>

Call f with the largest contiguous slice of octets in the receive buffer, without removing them from it.

If no data is available, it waits until there is at least one byte available.

Source

pub fn try_peek_with<R>( &mut self, f: impl FnOnce(&[u8]) -> R, ) -> Result<R, TryError<Error>>

Call f with the largest contiguous slice of octets in the receive buffer, without removing them from it.

This method will not wait for data to be received.

If no data is available, this method will return Err(TryError::WouldBlock).

Source

pub fn split(&mut self) -> (TcpReader<'_, 'd>, TcpWriter<'_, 'd>)

Split the socket into reader and a writer halves.

Source

pub fn bind_to_iface( &mut self, iface: Option<IfaceHandle>, ) -> Result<(), ConnectError>

Bind the socket to an interface, or unbind it with None.

A socket bound to an interface only sends and receives packets on it:

  • Destinations must be on-link on that iface, or have a route through it.
  • Broadcast and multicast destinations go out on that iface only
  • Local addresses will be picked from that iface only.

The socket must be closed (see is_open). The binding is kept across connections, so a reused socket stays bound to its interface. Accepting a connection into the socket overwrites it with the listener’s binding.

Two sockets with otherwise identical tuples may coexist if they are bound to different interfaces.

§Errors
  • InvalidState: if the socket is open.
Source

pub fn bound_iface(&self) -> Option<IfaceHandle>

Return the interface the socket is bound to, or None.

See bind_to_iface.

Source

pub async fn connect( &mut self, remote: impl Into<SocketAddr>, ) -> Result<(), ConnectError>

Connect to a given remote address, and wait until the connection is established.

The local port is an ephemeral port (a free port in the 49152..=65535 range, picked at a random starting point), and the local address is selected by the stack from the remote address.

§Errors
  • InvalidState: if the socket is open.
  • Unaddressable: if the remote port is zero, the remote address is unspecified, there is no route to the remote address, or the interface the route goes out of has no address to send from.
  • NoFreePorts: if the ephemeral range is exhausted.
  • InUse: if another TCP socket already holds the identical 4-tuple.
  • ConnectionReset: if the connection is reset or aborted during the handshake.
Source

pub async fn accept(&mut self, token: AcceptToken) -> Result<(), AcceptError>

Accept a connection attempt into this socket, and wait until its handshake completes.

The token comes from TcpListener::accept.

The socket’s interface binding (see bind_to_iface) is set to the listener’s binding. Other configuration (hop limit, timeout, keep-alive, Nagle, ACK delay) is left unchanged.

If the returned future is dropped before it completes, the connection attempt is reset.

§Errors
  • InvalidState: if the socket is not closed.
  • ConnectionReset: if the remote resets the connection during the handshake.
Source

pub fn try_connect( &mut self, remote: impl Into<SocketAddr>, ) -> Result<(), TryError<ConnectError>>

Connect to a remote host.

This method will not wait for the connection to be established.

If the socket is not already connecting, this method will initiate the connection and return Err(TryError::WouldBlock). While the connection is being established, it will continue to return Err(TryError::WouldBlock).

Once the connection is successfully established and ready to send/receive data, this method will return Ok(()).

Source

pub fn wait_read_ready(&self) -> impl Future<Output = ()> + '_

Wait until the socket becomes readable.

A socket becomes readable when the receive half of the full-duplex connection is open (see may_recv), and there is some pending data in the receive buffer.

This is the equivalent of read, without buffering any data.

Source

pub fn read<'s>( &'s mut self, buf: &'s mut [u8], ) -> impl Future<Output = Result<usize, Error>> + 's

Read data from the socket.

Returns how many bytes were read, or an error. If no data is available, it waits until there is at least one byte available.

A return value of Ok(0) means that the socket was closed and is longer able to receive any data.

Source

pub fn try_read(&mut self, buf: &mut [u8]) -> Result<usize, TryError<Error>>

Read data from the socket.

This method will not wait for data to be received.

If no data is available, this method will return Err(TryError::WouldBlock).

Source

pub fn wait_write_ready(&self) -> impl Future<Output = ()> + '_

Wait until the socket becomes writable.

A socket becomes writable when the transmit half of the full-duplex connection is open (see may_send), and the transmit buffer is not full.

This is the equivalent of write, without sending any data.

Source

pub fn write<'s>( &'s mut self, buf: &'s [u8], ) -> impl Future<Output = Result<usize, Error>> + 's

Write data to the socket.

Returns how many bytes were written, or an error. If the socket is not ready to accept data, it waits until it is.

Source

pub fn try_write(&mut self, buf: &[u8]) -> Result<usize, TryError<Error>>

Write data to the socket.

This method will not wait for the buffer to become free.

If the socket’s send buffer is full, this method will return Err(TryError::WouldBlock).

Source

pub fn flush(&mut self) -> impl Future<Output = Result<(), Error>> + '_

Flushes the written data to the socket.

This waits until all data has been sent, and ACKed by the remote host. For a connection closed with abort() it will wait for the TCP RST packet to be sent.

Source

pub fn try_flush(&mut self) -> Result<(), TryError<Error>>

Try to flush the socket.

This method will check if the socket is flushed, and if not, return Err(TryError::WouldBlock).

Source

pub fn set_timeout(&mut self, duration: Option<Duration>)

Set the timeout duration.

A socket with a timeout duration set will abort the connection if either of the following occurs:

  • After a connect call, the remote peer does not respond within the specified duration;
  • After establishing a connection, there is data in the transmit buffer and the remote peer exceeds the specified duration between any two packets it sends;
  • After enabling keep-alive, the remote peer exceeds the specified duration between any two packets it sends.
Source

pub fn timeout(&self) -> Option<Duration>

Return the timeout duration.

See also the set_timeout method.

Source

pub fn set_ack_delay(&mut self, duration: Option<Duration>)

Set the ACK delay duration.

By default, the ACK delay is set to 10ms.

Source

pub fn ack_delay(&self) -> Option<Duration>

Return the ACK delay duration.

See also the set_ack_delay method.

Source

pub fn set_keep_alive(&mut self, interval: Option<Duration>)

Set the keep-alive interval.

An idle socket with a keep-alive interval set will transmit a “keep-alive ACK” packet every time it receives no communication during that interval. As a result, three things may happen:

  • The remote peer is fine and answers with an ACK packet.
  • The remote peer has rebooted and answers with an RST packet.
  • The remote peer has crashed and does not answer.

The keep-alive functionality together with the timeout functionality allows to react to these error conditions.

Source

pub fn keep_alive(&self) -> Option<Duration>

Return the keep-alive interval.

See also the set_keep_alive method.

Source

pub fn set_hop_limit( &mut self, hop_limit: Option<u8>, ) -> Result<(), InvalidHopLimit>

Set the time-to-live (IPv4) or hop limit (IPv6) value used in outgoing packets.

A socket without an explicitly set hop limit value uses the default IANA recommended value (64).

§Errors
  • InvalidHopLimit: if the hop limit is Some(0). A host must not send a packet with a hop limit of zero (RFC 1122 § 3.2.1.7). The socket is left unchanged.
Source

pub fn hop_limit(&self) -> Option<u8>

Return the time-to-live (IPv4) or hop limit (IPv6) value used in outgoing packets.

See also the set_hop_limit method

Source

pub fn set_nagle_enabled(&mut self, enabled: bool)

Enable or disable Nagle’s Algorithm.

Also known as “tinygram prevention”. By default, it is enabled. Disabling it is equivalent to Linux’s TCP_NODELAY flag.

When enabled, Nagle’s Algorithm prevents sending segments smaller than MSS if there is data in flight (sent but not acknowledged). In other words, it ensures at most only one segment smaller than MSS is in flight at a time.

It ensures better network utilization by preventing sending many very small packets, at the cost of increased latency in some situations, particularly when the remote peer has ACK delay enabled.

Source

pub fn nagle_enabled(&self) -> bool

Return whether Nagle’s Algorithm is enabled.

See also the set_nagle_enabled method.

Source

pub fn local_addr(&self) -> Option<SocketAddr>

Return the local address, or None if not connected.

Source

pub fn remote_addr(&self) -> Option<SocketAddr>

Return the remote address, or None if not connected.

Source

pub fn state(&self) -> State

Return the connection state, in terms of the TCP state machine.

Source

pub fn is_open(&self) -> bool

Return whether the socket is open.

This function returns true if the socket will process incoming or dispatch outgoing packets. Note that this does not mean that it is possible to send or receive data through the socket; for that, use can_send or can_recv.

In terms of the TCP state machine, the socket must not be in the CLOSED or TIME-WAIT states.

Source

pub fn is_active(&self) -> bool

Return whether a connection is active.

This function returns true if the socket is actively exchanging packets with a remote peer. Note that this does not mean that it is possible to send or receive data through the socket; for that, use can_send or can_recv.

If a connection is established, abort will send a reset to the remote peer.

In terms of the TCP state machine, the socket must not be in the CLOSED or TIME-WAIT state.

Source

pub fn close(&mut self)

Close the transmit half of the full-duplex connection.

Data that has been written to the socket and not yet sent (or not yet ACKed) will still be sent. The last segment of the pending to send data is sent with the FIN flag set.

Note that there is no corresponding function for the receive half of the full-duplex connection; only the remote end can close it. If you no longer wish to receive any data and would like to reuse the socket right away, use abort.

Source

pub fn abort(&mut self)

Aborts the connection, if any.

This function instantly closes the socket. One reset packet will be sent to the remote peer.

In terms of the TCP state machine, the socket may be in any state and is moved to the CLOSED state.

Note that the TCP RST packet is not sent immediately - if the TcpSocket is dropped too soon the remote host may not know the connection has been closed. abort() callers should wait for a flush() call to complete before dropping or reusing the socket.

Source

pub fn may_send(&self) -> bool

Return whether the transmit half of the full-duplex connection is open.

This function returns true if it’s possible to send data and have it arrive to the remote peer. However, it does not make any guarantees about the state of the transmit buffer, and even if it returns true, write may not be able to enqueue any octets.

In terms of the TCP state machine, the socket must be in the ESTABLISHED or CLOSE-WAIT state.

Source

pub fn can_send(&self) -> bool

Check whether the transmit half of the full-duplex connection is open (see may_send), and the transmit buffer is not full.

Source

pub fn may_recv(&self) -> bool

Return whether the receive half of the full-duplex connection is open.

This function returns true if it’s possible to receive data from the remote peer. It will return true while there is data in the receive buffer, and if there isn’t, as long as the remote peer has not closed the connection.

In terms of the TCP state machine, the socket must be in the ESTABLISHED, FIN-WAIT-1, or FIN-WAIT-2 state, or have data in the receive buffer instead.

Source

pub fn can_recv(&self) -> bool

Check whether the receive buffer is not empty.

Trait Implementations§

Source§

impl Drop for TcpSocket<'_, '_>

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more
Source§

impl ErrorType for TcpSocket<'_, '_>

Source§

type Error = Error

Error type of all the IO operations on this type.
Source§

impl Read for TcpSocket<'_, '_>

Source§

async fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error>

Read some bytes from this source into the specified buffer, returning how many bytes were read. Read more
Source§

async fn read_exact( &mut self, buf: &mut [u8], ) -> Result<(), ReadExactError<Self::Error>>

Read the exact number of bytes required to fill buf. Read more
Source§

impl ReadReady for TcpSocket<'_, '_>

Source§

fn read_ready(&mut self) -> Result<bool, Self::Error>

Get whether the reader is ready for immediately reading. Read more
Source§

impl Write for TcpSocket<'_, '_>

Source§

async fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error>

Write a buffer into this writer, returning how many bytes were written. Read more
Source§

async fn flush(&mut self) -> Result<(), Self::Error>

Flush this output stream, ensuring that all intermediately buffered contents reach their destination.
Source§

async fn write_all(&mut self, buf: &[u8]) -> Result<(), Self::Error>

Write an entire buffer into this writer. Read more
Source§

impl WriteReady for TcpSocket<'_, '_>

Source§

fn write_ready(&mut self) -> Result<bool, Self::Error>

Get whether the writer is ready for immediately writing. Read more

Auto Trait Implementations§

§

impl<'a, 'd> !RefUnwindSafe for TcpSocket<'a, 'd>

§

impl<'a, 'd> !Send for TcpSocket<'a, 'd>

§

impl<'a, 'd> !Sync for TcpSocket<'a, 'd>

§

impl<'a, 'd> !UnwindSafe for TcpSocket<'a, 'd>

§

impl<'a, 'd> Freeze for TcpSocket<'a, 'd>

§

impl<'a, 'd> Unpin for TcpSocket<'a, 'd>

§

impl<'a, 'd> UnsafeUnpin for TcpSocket<'a, 'd>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.