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
impl TcpConnection
Sourcepub fn connect<A: ToSocketAddrs>(addr: A) -> Result<TcpConnection, NetError>
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.
Sourcepub fn connect_with<A: ToSocketAddrs>(
addr: A,
options: ConnectOptions,
) -> Result<TcpConnection, NetError>
pub fn connect_with<A: ToSocketAddrs>( addr: A, options: ConnectOptions, ) -> Result<TcpConnection, NetError>
Sourcepub fn connect_retry<A: ToSocketAddrs>(
addr: A,
options: ConnectOptions,
backoff: &mut Backoff,
) -> Result<TcpConnection, NetError>
pub fn connect_retry<A: ToSocketAddrs>( addr: A, options: ConnectOptions, backoff: &mut Backoff, ) -> Result<TcpConnection, NetError>
Connects, and after a failure a restarting or failing-over server produces
(refused, timed out, unreachable, reset, no addresses, resolution failed), or
a shortage of local ports (every ephemeral port in use or in TIME_WAIT),
sleeps for Backoff::next_delay and tries again, resolving addr again
each time. Any other error returns at once.
use net_io::{Backoff, ConnectOptions, TcpConnection};
use std::time::Duration;
let mut backoff = Backoff::new().give_up_after(Duration::from_secs(60));
let conn = TcpConnection::connect_retry("db.internal:5433", ConnectOptions::new(), &mut backoff)?;
backoff.reset();§Errors
The last connect error once backoff is spent; a non-transient error at once.
Sourcepub fn connect_host(
host: &str,
port: u16,
options: ConnectOptions,
) -> Result<TcpConnection, NetError>
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.
Sourcepub fn recv(&mut self, buf: &mut [u8]) -> Result<usize, NetError>
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.
Sourcepub fn recv_vectored(
&mut self,
bufs: &mut [IoSliceMut<'_>],
) -> Result<usize, NetError>
pub fn recv_vectored( &mut self, bufs: &mut [IoSliceMut<'_>], ) -> Result<usize, NetError>
Sourcepub fn peek(&self, buf: &mut [u8]) -> Result<usize, NetError>
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.
Sourcepub fn send(&mut self, buf: &[u8]) -> Result<usize, NetError>
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.
Sourcepub fn send_all(&mut self, buf: &[u8]) -> Result<(), NetError>
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
Sourcepub fn send_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize, NetError>
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
Sourcepub fn send_file(
&mut self,
file: &File,
offset: u64,
len: u64,
) -> Result<u64, NetError>
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.
Sourcepub fn recv_file(
&mut self,
file: &File,
offset: u64,
len: u64,
) -> Result<u64, NetError>
pub fn recv_file( &mut self, file: &File, offset: u64, len: u64, ) -> Result<u64, NetError>
Receives up to len bytes into file at offset, for snapshot and log
shipping; returns the count, which is short of len only when the peer
closed. On Linux the bytes go socket to pipe to file by splice, without a
copy through user space; with TLS, on other systems, and for a file splice
turns down, they are copied through a 64 KiB buffer. The read deadlines, the
minimum rate, kills, and drains apply as for TcpConnection::recv. The
file’s position does not matter, and on Unix it does not move; a file opened
for appending is written at its end whatever offset says.
let mut conn = net_io::connect("127.0.0.1:7000")?;
let file = std::fs::File::create("snapshot.bin")?;
let got = conn.recv_file(&file, 0, 1 << 30)?;
println!("received {got} bytes");§Errors
As TcpConnection::recv; Os when the file cannot be written, and the
connection is then closed.
Sourcepub fn probe(&mut self) -> Result<Health, NetError>
pub fn probe(&mut self) -> Result<Health, NetError>
What the next read would find, without waiting and without consuming: one zero-timeout wait, and a one-byte peek when the socket is readable. Use it before reusing an idle pooled connection; a request sent on a connection whose peer already closed is lost.
use net_io::Health;
let mut conn = net_io::connect("127.0.0.1:7000")?;
if conn.probe()? != Health::Open {
conn = net_io::connect("127.0.0.1:7000")?;
}§Errors
ConnectionReset when the peer reset it, Killed, Closed after a fatal
error, Os.
Sourcepub fn drain(self, within: Duration) -> Drained
pub fn drain(self, within: Duration) -> Drained
Client-side drain: FIN, then reads and discards until the peer’s FIN arrives
or within passes, then closes. Closing after the peer’s FIN leaves nothing
unread, so neither side sees a reset.
use std::time::Duration;
let conn = net_io::connect("127.0.0.1:7000")?;
let drained = conn.drain(Duration::from_secs(2));
println!("clean: {}, discarded {} bytes", drained.peer_closed, drained.discarded);Sourcepub fn close(self) -> Result<(), NetError>
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.
Sourcepub fn info(&self) -> &ConnectionInfo
pub fn info(&self) -> &ConnectionInfo
What net-io knows about this connection.
Sourcepub fn id(&self) -> ConnectionId
pub fn id(&self) -> ConnectionId
The connection’s id.
Sourcepub fn peer_addr(&self) -> SocketAddr
pub fn peer_addr(&self) -> SocketAddr
The socket peer.
Sourcepub fn local_addr(&self) -> SocketAddr
pub fn local_addr(&self) -> SocketAddr
Our end.
Sourcepub fn kill_handle(&self) -> KillHandle
pub fn kill_handle(&self) -> KillHandle
A handle other threads can use to abort this connection.
Sourcepub fn set_limits(&mut self, limits: Limits)
pub fn set_limits(&mut self, limits: Limits)
Replaces the limits from the next operation on (unset values: blocking-driver defaults).
Sourcepub fn set_exchange_deadline(&mut self, at: Option<Instant>)
pub fn set_exchange_deadline(&mut self, at: Option<Instant>)
The deadline for the current exchange (None clears it).
Sourcepub fn set_gate<G: Gate>(&mut self, gate: Arc<G>) -> Result<(), NetError>
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")?;Sourcepub fn options(&self) -> SocketOptions<'_>
pub fn options(&self) -> SocketOptions<'_>
Live socket options.
Trait Implementations§
Source§impl AsFd for TcpConnection
Available on Unix only.
impl AsFd for TcpConnection
Source§fn as_fd(&self) -> BorrowedFd<'_>
fn as_fd(&self) -> BorrowedFd<'_>
Source§impl Debug for TcpConnection
impl Debug for TcpConnection
Source§impl Drop for TcpConnection
impl Drop for TcpConnection
Source§impl Read for TcpConnection
impl Read for TcpConnection
Source§fn read(&mut self, buf: &mut [u8]) -> Result<usize>
fn read(&mut self, buf: &mut [u8]) -> Result<usize>
1.36.0 · Source§fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize, Error>
fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize, Error>
read, except that it reads into a slice of buffers. Read moreSource§fn is_read_vectored(&self) -> bool
fn is_read_vectored(&self) -> bool
can_vector)1.0.0 · Source§fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize, Error>
fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize, Error>
buf. Read more1.0.0 · Source§fn read_to_string(&mut self, buf: &mut String) -> Result<usize, Error>
fn read_to_string(&mut self, buf: &mut String) -> Result<usize, Error>
buf. Read more1.6.0 · Source§fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), Error>
fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), Error>
buf. Read moreSource§fn read_buf(&mut self, buf: BorrowedCursor<'_, u8>) -> Result<(), Error>
fn read_buf(&mut self, buf: BorrowedCursor<'_, u8>) -> Result<(), Error>
read_buf)Source§fn read_buf_exact(
&mut self,
cursor: BorrowedCursor<'_, u8>,
) -> Result<(), Error>
fn read_buf_exact( &mut self, cursor: BorrowedCursor<'_, u8>, ) -> Result<(), Error>
read_buf)cursor. Read more1.0.0 · Source§fn by_ref(&mut self) -> &mut Selfwhere
Self: Sized,
fn by_ref(&mut self) -> &mut Selfwhere
Self: Sized,
Read. Read more1.0.0 · Source§fn chain<R>(self, next: R) -> Chain<Self, R> ⓘ
fn chain<R>(self, next: R) -> Chain<Self, R> ⓘ
1.0.0 · Source§fn take(self, limit: u64) -> Take<Self> ⓘwhere
Self: Sized,
fn take(self, limit: u64) -> Take<Self> ⓘwhere
Self: Sized,
limit bytes from it. Read moreSource§fn read_array<const N: usize>(&mut self) -> Result<[u8; N], Error>where
Self: Sized,
fn read_array<const N: usize>(&mut self) -> Result<[u8; N], Error>where
Self: Sized,
read_array)Source§impl Write for TcpConnection
impl Write for TcpConnection
Source§fn write(&mut self, buf: &[u8]) -> Result<usize>
fn write(&mut self, buf: &[u8]) -> Result<usize>
Source§fn flush(&mut self) -> Result<()>
fn flush(&mut self) -> Result<()>
Source§fn is_write_vectored(&self) -> bool
fn is_write_vectored(&self) -> bool
can_vector)1.0.0 · Source§fn write_all(&mut self, buf: &[u8]) -> Result<(), Error>
fn write_all(&mut self, buf: &[u8]) -> Result<(), Error>
Source§fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<(), Error>
fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<(), Error>
write_all_vectored)