Skip to main content

TcpConnection

Struct TcpConnection 

Source
pub struct TcpConnection { /* private fields */ }
Expand description

A connected TCP socket that carries its own limits.

Every read honours the current phase’s deadline (a connection from accept starts Idle under the idle timeout; one from connect starts Receiving under the read timeout), the exchange deadline, and the inbound minimum rate; every write honours the write deadline and the outbound minimum rate. One owner: other threads act on it only through its KillHandle.

§Examples

use net_io::{Limits, Phase};
use std::time::{Duration, Instant};

let mut conn = net_io::connect("127.0.0.1:7000")?;
conn.set_limits(Limits::builder().read_timeout(Duration::from_secs(5)).build()?);
conn.set_phase(Phase::Receiving);
conn.set_exchange_deadline(Some(Instant::now() + Duration::from_secs(20)));
let mut buf = [0u8; 1024];
let n = conn.recv(&mut buf)?;

Implementations§

Source§

impl TcpConnection

Source

pub fn connect<A: ToSocketAddrs>(addr: A) -> Result<TcpConnection, NetError>

Connects with a 10 s timeout across every resolved address (see crate::connect).

§Errors

ConnectTimeout, ConnectionRefused, HostUnreachable, NetworkUnreachable, NoAddresses.

Source

pub fn connect_with<A: ToSocketAddrs>( addr: A, options: ConnectOptions, ) -> Result<TcpConnection, NetError>

Connects with options.

§Errors

As TcpConnection::connect.

Source

pub fn connect_host( host: &str, port: u16, options: ConnectOptions, ) -> Result<TcpConnection, NetError>

Resolves host with the standard library and connects to the addresses in order; each attempt gets the remaining time divided by the remaining addresses (at least 1 s).

§Errors

NoAddresses, or the last connect error.

Source

pub fn recv(&mut self, buf: &mut [u8]) -> Result<usize, NetError>

One receive; Ok(0) means the peer closed its side. A zero-length buf returns Ok(0) without a system call (check buf.len()).

§Errors

TimedOut { kind }, SlowPeer { In }, ConnectionReset, Killed, Closed.

Source

pub fn recv_exact(&mut self, buf: &mut [u8]) -> Result<(), NetError>

Receives until buf is full.

§Errors

As TcpConnection::recv; Closed when the peer closes first.

Source

pub fn recv_vectored( &mut self, bufs: &mut [IoSliceMut<'_>], ) -> Result<usize, NetError>

One receive into the first non-empty slice.

§Errors

As TcpConnection::recv.

Source

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

Reads without consuming (MSG_PEEK), within the read timeout.

§Errors

As TcpConnection::recv; Unsupported on a TLS connection.

Source

pub fn send(&mut self, buf: &[u8]) -> Result<usize, NetError>

One send after the gate check; may be partial.

§Errors

TimedOut, SlowPeer { Out }, BrokenPipe, ConnectionReset, EgressDenied, Killed.

Source

pub fn send_all(&mut self, buf: &[u8]) -> Result<(), NetError>

Sends all of buf, continuing from the exact offset; the gate check runs before every system call.

§Errors

As TcpConnection::send.

Source

pub fn send_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize, NetError>

One vectored send (up to 64 slices) after the gate check; may be partial.

§Errors

As TcpConnection::send.

Source

pub fn send_file( &mut self, file: &File, offset: u64, len: u64, ) -> Result<u64, NetError>

Sends len bytes of file from offset: zero copy where the OS can (sendfile on Unix), by reading and writing otherwise (TLS; Windows outside the reactor). A gate check runs before each 1 MiB. The file’s position does not matter, and on Unix it does not move.

§Errors

As TcpConnection::send; FileTruncated { sent } when the file ends early, and the connection is then reset. Send files that do not change while in flight.

Source

pub fn send_all_vectored( &mut self, bufs: &mut [IoSlice<'_>], ) -> Result<(), NetError>

Sends every slice, advancing them in place (no copy).

§Errors

As TcpConnection::send.

Source

pub fn shutdown(&mut self, how: Shutdown) -> Result<(), NetError>

Half-close: Write sends FIN and keeps reading; Read stops reading.

§Errors

Closed, Os.

Source

pub fn close(self) -> Result<(), NetError>

Graceful close: FIN, then reads and discards up to 64 KiB for up to 2 s so unread input does not cause an RST that destroys the last response.

§Errors

None in this version; the signature leaves room for a flush error.

Source

pub fn abort(self)

Abortive close: RST, kernel resources freed at once.

Source

pub fn info(&self) -> &ConnectionInfo

What net-io knows about this connection.

Source

pub fn id(&self) -> ConnectionId

The connection’s id.

Source

pub fn peer_addr(&self) -> SocketAddr

The socket peer.

Source

pub fn local_addr(&self) -> SocketAddr

Our end.

Source

pub fn kill_handle(&self) -> KillHandle

A handle other threads can use to abort this connection.

Source

pub fn set_limits(&mut self, limits: Limits)

Replaces the limits from the next operation on (unset values: blocking-driver defaults).

Source

pub fn set_phase(&mut self, phase: Phase)

Chooses which deadlines apply.

Source

pub fn set_exchange_deadline(&mut self, at: Option<Instant>)

The deadline for the current exchange (None clears it).

Source

pub fn set_gate<G: Gate>(&mut self, gate: Arc<G>) -> Result<(), NetError>

Registers this dialed connection with gate (Gate::admit with AdmitStage::Dialed): from then on Gate::check runs before every write and Gate::closed runs once at close, so a back-channel or outbound connection can be revoked like an accepted one.

§Errors

Refused { cause: Gate(code) } when the gate refuses (the connection is then aborted and later calls return Closed); InvalidConfig { field: "gate" } when a gate is already set; Closed.

use std::sync::Arc;
let mut upstream = net_io::connect("10.0.0.9:9000")?;
upstream.set_gate(Arc::new(net_io::AllowAll))?;
upstream.send_all(b"PING\r\n")?;
Source

pub fn options(&self) -> SocketOptions<'_>

Live socket options.

Source

pub fn take_error(&self) -> Result<Option<Error>, NetError>

The socket’s pending error (SO_ERROR).

§Errors

Os when the OS call fails.

Trait Implementations§

Source§

impl AsFd for TcpConnection

Available on Unix only.
Source§

fn as_fd(&self) -> BorrowedFd<'_>

Borrows the file descriptor. Read more
Source§

impl Debug for TcpConnection

Source§

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

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

impl Drop for TcpConnection

Source§

fn drop(&mut self)

Never blocks: FIN, then close without the linger; use close() for the full graceful close.

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 Read for TcpConnection

Source§

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

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

fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize, Error>

Like read, except that it reads into a slice of buffers. Read more
Source§

fn is_read_vectored(&self) -> bool

🔬This is a nightly-only experimental API. (can_vector)
Determines if this Reader has an efficient read_vectored implementation. Read more
1.0.0 · Source§

fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize, Error>

Reads all bytes until EOF in this source, placing them into buf. Read more
1.0.0 · Source§

fn read_to_string(&mut self, buf: &mut String) -> Result<usize, Error>

Reads all bytes until EOF in this source, appending them to buf. Read more
1.6.0 · Source§

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

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

fn read_buf(&mut self, buf: BorrowedCursor<'_, u8>) -> Result<(), Error>

🔬This is a nightly-only experimental API. (read_buf)
Pull some bytes from this source into the specified buffer. Read more
Source§

fn read_buf_exact( &mut self, cursor: BorrowedCursor<'_, u8>, ) -> Result<(), Error>

🔬This is a nightly-only experimental API. (read_buf)
Reads the exact number of bytes required to fill cursor. Read more
1.0.0 · Source§

fn by_ref(&mut self) -> &mut Self
where Self: Sized,

Creates a “by reference” adapter for this instance of Read. Read more
1.0.0 · Source§

fn bytes(self) -> Bytes<Self> ⓘ
where Self: Sized,

Transforms this Read instance to an Iterator over its bytes. Read more
1.0.0 · Source§

fn chain<R>(self, next: R) -> Chain<Self, R> ⓘ
where R: Read, Self: Sized,

Creates an adapter which will chain this stream with another. Read more
1.0.0 · Source§

fn take(self, limit: u64) -> Take<Self> ⓘ
where Self: Sized,

Creates an adapter which will read at most limit bytes from it. Read more
Source§

fn read_array<const N: usize>(&mut self) -> Result<[u8; N], Error>
where Self: Sized,

🔬This is a nightly-only experimental API. (read_array)
Read and return a fixed array of bytes from this source. Read more
Source§

fn read_le<T>(&mut self) -> Result<T, Error>
where T: FromEndianBytes, Self: Sized,

🔬This is a nightly-only experimental API. (read_le)
Read and return a type (e.g. an integer) in little-endian order. Read more
Source§

fn read_be<T>(&mut self) -> Result<T, Error>
where T: FromEndianBytes, Self: Sized,

🔬This is a nightly-only experimental API. (read_le)
Read and return a type (e.g. an integer) in big-endian order. Read more
Source§

impl Write for TcpConnection

Source§

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

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

fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize>

Like write, except that it writes from a slice of buffers. Read more
Source§

fn flush(&mut self) -> Result<()>

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

fn is_write_vectored(&self) -> bool

🔬This is a nightly-only experimental API. (can_vector)
Determines if this Writer has an efficient write_vectored implementation. Read more
1.0.0 · Source§

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

Attempts to write an entire buffer into this writer. Read more
Source§

fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<(), Error>

🔬This is a nightly-only experimental API. (write_all_vectored)
Attempts to write multiple buffers into this writer. Read more
1.0.0 · Source§

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

Writes a formatted string into this writer, returning any error encountered. Read more
1.0.0 · Source§

fn by_ref(&mut self) -> &mut Self
where Self: Sized,

Creates a “by reference” adapter for this instance of Write. Read more

Auto Trait Implementations§

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

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.