Struct smoltcp::socket::tcp::Socket

source ·
pub struct Socket<'a> { /* private fields */ }
Expand description

A Transmission Control Protocol socket.

A TCP socket may passively listen for connections or actively connect to another endpoint. Note that, for listening sockets, there is no “backlog”; to be able to simultaneously accept several connections, as many sockets must be allocated, or any new connection attempts will be reset.

Implementations§

source§

impl<'a> Socket<'a>

source

pub fn new<T>(rx_buffer: T, tx_buffer: T) -> Socket<'a>
where T: Into<SocketBuffer<'a>>,

Create a socket using the given buffers.

source

pub fn register_recv_waker(&mut self, waker: &Waker)

Register a waker for receive operations.

The waker is woken on state changes that might affect the return value of recv method calls, such as receiving data, or the socket closing.

Notes:

  • Only one waker can be registered at a time. If another waker was previously registered, it is overwritten and will no longer be woken.
  • The Waker is woken only once. Once woken, you must register it again to receive more wakes.
  • “Spurious wakes” are allowed: a wake doesn’t guarantee the result of recv has necessarily changed.
source

pub fn register_send_waker(&mut self, waker: &Waker)

Register a waker for send operations.

The waker is woken on state changes that might affect the return value of send method calls, such as space becoming available in the transmit buffer, or the socket closing.

Notes:

  • Only one waker can be registered at a time. If another waker was previously registered, it is overwritten and will no longer be woken.
  • The Waker is woken only once. Once woken, you must register it again to receive more wakes.
  • “Spurious wakes” are allowed: a wake doesn’t guarantee the result of send has necessarily changed.
source

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

Return the timeout duration.

See also the set_timeout method.

source

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

Return the ACK delay duration.

See also the set_ack_delay method.

source

pub fn nagle_enabled(&self) -> bool

Return whether Nagle’s Algorithm is enabled.

See also the set_nagle_enabled method.

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 endpoint does not respond within the specified duration;
  • After establishing a connection, there is data in the transmit buffer and the remote endpoint exceeds the specified duration between any two packets it sends;
  • After enabling keep-alive, the remote endpoint exceeds the specified duration between any two packets it sends.
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 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 keep_alive(&self) -> Option<Duration>

Return the keep-alive interval.

See also the set_keep_alive 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 endpoint is fine and answers with an ACK packet.
  • The remote endpoint has rebooted and answers with an RST packet.
  • The remote endpoint 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 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_hop_limit(&mut self, hop_limit: Option<u8>)

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

Panics

This function panics if a hop limit value of 0 is given. See RFC 1122 § 3.2.1.7.

source

pub fn local_endpoint(&self) -> Option<IpEndpoint>

Return the local endpoint, or None if not connected.

source

pub fn remote_endpoint(&self) -> Option<IpEndpoint>

Return the remote endpoint, 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 listen<T>(&mut self, local_endpoint: T) -> Result<(), ListenError>

Start listening on the given endpoint.

This function returns Err(Error::InvalidState) if the socket was already open (see is_open), and Err(Error::Unaddressable) if the port in the given endpoint is zero.

source

pub fn connect<T, U>( &mut self, cx: &mut Context, remote_endpoint: T, local_endpoint: U ) -> Result<(), ConnectError>

Connect to a given endpoint.

The local port must be provided explicitly. Assuming fn get_ephemeral_port() -> u16 allocates a port between 49152 and 65535, a connection may be established as follows:

socket.connect(
    iface.context(),
    (IpAddress::v4(10, 0, 0, 1), 80),
    get_ephemeral_port()
).unwrap();

The local address may optionally be provided.

This function returns an error if the socket was open; see is_open. It also returns an error if the local or remote port is zero, or if the remote address is unspecified.

source

pub fn close(&mut self)

Close the transmit half of the full-duplex connection.

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

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

source

pub fn is_listening(&self) -> bool

Return whether the socket is passively listening for incoming connections.

In terms of the TCP state machine, the socket must be in the LISTEN state.

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

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

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 endpoint. However, it does not make any guarantees about the state of the transmit buffer, and even if it returns true, send 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 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 endpoint. It will return true while there is data in the receive buffer, and if there isn’t, as long as the remote endpoint 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_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 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 can_recv(&self) -> bool

Check whether the receive half of the full-duplex connection buffer is open (see may_recv), and the receive buffer is not empty.

source

pub fn send<'b, F, R>(&'b mut self, f: F) -> Result<R, SendError>
where F: FnOnce(&'b mut [u8]) -> (usize, R),

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

This function returns Err(Error::Illegal) if the transmit half of the connection is not open; see may_send.

source

pub fn send_slice(&mut self, data: &[u8]) -> Result<usize, SendError>

Enqueue a sequence of octets to be sent, and fill it from a slice.

This function returns the amount of octets actually enqueued, which is limited by the amount of free space in the transmit buffer; down to zero.

See also send.

source

pub fn recv<'b, F, R>(&'b mut self, f: F) -> Result<R, RecvError>
where F: FnOnce(&'b mut [u8]) -> (usize, R),

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

This function errors if the receive half of the connection is not open.

If the receive half has been gracefully closed (with a FIN packet), Err(Error::Finished) is returned. In this case, the previously received data is guaranteed to be complete.

In all other cases, Err(Error::Illegal) is returned and previously received data (if any) may be incomplete (truncated).

source

pub fn recv_slice(&mut self, data: &mut [u8]) -> Result<usize, RecvError>

Dequeue a sequence of received octets, and fill a slice from it.

This function returns the amount of octets actually dequeued, which is limited by the amount of occupied space in the receive buffer; down to zero.

See also recv.

source

pub fn peek(&mut self, size: usize) -> Result<&[u8], RecvError>

Peek at a sequence of received octets without removing them from the receive buffer, and return a pointer to it.

This function otherwise behaves identically to recv.

source

pub fn peek_slice(&mut self, data: &mut [u8]) -> Result<usize, RecvError>

Peek at a sequence of received octets without removing them from the receive buffer, and fill a slice from it.

This function otherwise behaves identically to recv_slice.

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.

Trait Implementations§

source§

impl<'a> AnySocket<'a> for Socket<'a>

source§

fn upcast(self) -> Socket<'a>

source§

fn downcast<'c>(socket: &'c Socket<'a>) -> Option<&'c Self>

source§

fn downcast_mut<'c>(socket: &'c mut Socket<'a>) -> Option<&'c mut Self>

source§

impl<'a> Debug for Socket<'a>

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl<'a> Write for Socket<'a>

source§

fn write_str(&mut self, slice: &str) -> Result

Writes a string slice into this writer, returning whether the write succeeded. Read more
1.1.0 · source§

fn write_char(&mut self, c: char) -> Result<(), Error>

Writes a char into this writer, returning whether the write succeeded. Read more
1.0.0 · source§

fn write_fmt(&mut self, args: Arguments<'_>) -> Result<(), Error>

Glue for usage of the write! macro with implementors of this trait. Read more

Auto Trait Implementations§

§

impl<'a> RefUnwindSafe for Socket<'a>

§

impl<'a> Send for Socket<'a>

§

impl<'a> Sync for Socket<'a>

§

impl<'a> Unpin for Socket<'a>

§

impl<'a> !UnwindSafe for Socket<'a>

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>,

§

type Error = Infallible

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>,

§

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.