Struct TcpStream
pub struct TcpStream(pub(in ::net::tcp) TcpStream);
A TCP stream between a local and a remote socket.
After creating a TcpStream by either connecting to a remote host or
accepting a connection on a TcpListener, data can be transmitted
by reading and writing to it.
The connection will be closed when the value is dropped. The reading and writing
portions of the connection can also be shut down individually with the shutdown
method.
The Transmission Control Protocol is specified in IETF RFC 793.
Examples
use std::io::prelude::*;
use std::net::TcpStream;
fn main() -> std::io::Result<()> {
let mut stream = TcpStream::connect("127.0.0.1:34254")?;
stream.write(&[1])?;
stream.read(&mut [0; 128])?;
Ok(())
} // the stream is closed here
Platform-specific Behavior
On Unix, writes to the underlying socket in SOCK_STREAM mode are made with
MSG_NOSIGNAL flag. This suppresses the emission of the SIGPIPE signal when writing
to disconnected socket. In some cases, getting a SIGPIPE would trigger process termination.
Fields
0: TcpStream
Implementations
impl TcpStream
fn connect<A: ToSocketAddrs>(addr: A) -> Result<TcpStream>Opens a TCP connection to a remote host.
addris an address of the remote host. Anything which implementsToSocketAddrstrait can be supplied for the address; see this trait documentation for concrete examples.If
addryields multiple addresses,connectwill be attempted with each of the addresses until a connection is successful. If none of the addresses result in a successful connection, the error returned from the last connection attempt (the last address) is returned.Examples
Open a TCP connection to
127.0.0.1:8080:use std::net::TcpStream; if let Ok(stream) = TcpStream::connect("127.0.0.1:8080") { println!("Connected to the server!"); } else { println!("Couldn't connect to server..."); }Open a TCP connection to
127.0.0.1:8080. If the connection fails, open a TCP connection to127.0.0.1:8081:use std::net::{SocketAddr, TcpStream}; let addrs = [ SocketAddr::from(([127, 0, 0, 1], 8080)), SocketAddr::from(([127, 0, 0, 1], 8081)), ]; if let Ok(stream) = TcpStream::connect(&addrs[..]) { println!("Connected to the server!"); } else { println!("Couldn't connect to server..."); }fn connect_timeout(addr: &SocketAddr, timeout: Duration) -> Result<TcpStream>Opens a TCP connection to a remote host with a timeout.
Unlike
connect,connect_timeouttakes a singleSocketAddrsince timeout must be applied to individual addresses.It is an error to pass a zero
Durationto this function.Unlike other methods on
TcpStream, this does not correspond to a single system call. It instead callsconnectin nonblocking mode and then uses an OS-specific mechanism to await the completion of the connection request.fn peer_addr(&self) -> Result<SocketAddr>Returns the socket address of the remote peer of this TCP connection.
Examples
use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpStream}; let stream = TcpStream::connect("127.0.0.1:8080") .expect("Couldn't connect to the server..."); assert_eq!(stream.peer_addr().unwrap(), SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));fn local_addr(&self) -> Result<SocketAddr>Returns the socket address of the local half of this TCP connection.
Examples
use std::net::{IpAddr, Ipv4Addr, TcpStream}; let stream = TcpStream::connect("127.0.0.1:8080") .expect("Couldn't connect to the server..."); assert_eq!(stream.local_addr().unwrap().ip(), IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));fn shutdown(&self, how: Shutdown) -> Result<()>Shuts down the read, write, or both halves of this connection.
This function will cause all pending and future I/O on the specified portions to return immediately with an appropriate value (see the documentation of
Shutdown).Platform-specific behavior
Calling this function multiple times may result in different behavior, depending on the operating system. On Linux, the second call will return
Ok(()), but on macOS, it will returnErrorKind::NotConnected. This may change in the future.Examples
use std::net::{Shutdown, TcpStream}; let stream = TcpStream::connect("127.0.0.1:8080") .expect("Couldn't connect to the server..."); stream.shutdown(Shutdown::Both).expect("shutdown should succeed");fn try_clone(&self) -> Result<TcpStream>Creates a new independently owned handle to the underlying socket.
The returned
TcpStreamis a reference to the same stream that this object references. Both handles will read and write the same stream of data, and options set on one stream will be propagated to the other stream.Examples
use std::net::TcpStream; let stream = TcpStream::connect("127.0.0.1:8080") .expect("Couldn't connect to the server..."); let stream_clone = stream.try_clone().expect("clone should succeed");fn set_read_timeout(&self, dur: Option<Duration>) -> Result<()>Sets the read timeout to the timeout specified.
If the value specified is
None, thenreadcalls will block indefinitely. AnErris returned if the zeroDurationis passed to this method.Platform-specific behavior
Platforms may return a different error code whenever a read times out as a result of setting this option. For example Unix typically returns an error of the kind
WouldBlock, but Windows may returnTimedOut.Examples
use std::net::TcpStream; let stream = TcpStream::connect("127.0.0.1:8080") .expect("Couldn't connect to the server..."); stream.set_read_timeout(None).expect("set_read_timeout should succeed");An
Erris returned if the zeroDurationis passed to this method:use std::io; use std::net::TcpStream; use std::time::Duration; let stream = TcpStream::connect("127.0.0.1:8080").unwrap(); let result = stream.set_read_timeout(Some(Duration::new(0, 0))); let err = result.unwrap_err(); assert_eq!(err.kind(), io::ErrorKind::InvalidInput)fn set_write_timeout(&self, dur: Option<Duration>) -> Result<()>Sets the write timeout to the timeout specified.
If the value specified is
None, thenwritecalls will block indefinitely. AnErris returned if the zeroDurationis passed to this method.Platform-specific behavior
Platforms may return a different error code whenever a write times out as a result of setting this option. For example Unix typically returns an error of the kind
WouldBlock, but Windows may returnTimedOut.Examples
use std::net::TcpStream; let stream = TcpStream::connect("127.0.0.1:8080") .expect("Couldn't connect to the server..."); stream.set_write_timeout(None).expect("set_write_timeout should succeed");An
Erris returned if the zeroDurationis passed to this method:use std::io; use std::net::TcpStream; use std::time::Duration; let stream = TcpStream::connect("127.0.0.1:8080").unwrap(); let result = stream.set_write_timeout(Some(Duration::new(0, 0))); let err = result.unwrap_err(); assert_eq!(err.kind(), io::ErrorKind::InvalidInput)fn read_timeout(&self) -> Result<Option<Duration>>Returns the read timeout of this socket.
If the timeout is
None, thenreadcalls will block indefinitely.Platform-specific behavior
Some platforms do not provide access to the current timeout.
Examples
use std::net::TcpStream; let stream = TcpStream::connect("127.0.0.1:8080") .expect("Couldn't connect to the server..."); stream.set_read_timeout(None).expect("set_read_timeout should succeed"); assert_eq!(stream.read_timeout().unwrap(), None);fn write_timeout(&self) -> Result<Option<Duration>>Returns the write timeout of this socket.
If the timeout is
None, thenwritecalls will block indefinitely.Platform-specific behavior
Some platforms do not provide access to the current timeout.
Examples
use std::net::TcpStream; let stream = TcpStream::connect("127.0.0.1:8080") .expect("Couldn't connect to the server..."); stream.set_write_timeout(None).expect("set_write_timeout should succeed"); assert_eq!(stream.write_timeout().unwrap(), None);fn peek(&self, buf: &mut [u8]) -> Result<usize>Receives data on the socket from the remote address to which it is connected, without removing that data from the queue. On success, returns the number of bytes peeked.
Successive calls return the same data. This is accomplished by passing
MSG_PEEKas a flag to the underlyingrecvsystem call.Examples
use std::net::TcpStream; let stream = TcpStream::connect("127.0.0.1:8000") .expect("Couldn't connect to the server..."); let mut buf = [0; 10]; let len = stream.peek(&mut buf).expect("peek should succeed");fn set_linger(&self, linger: Option<Duration>) -> Result<()>Sets the value of the
SO_LINGERoption on this socket.This value controls how the socket is closed when data remains to be sent. If
SO_LINGERis set, the socket will remain open for the specified duration as the system attempts to send pending data. Otherwise, the system may close the socket immediately, or wait for a default timeout.Examples
#![feature(tcp_linger)] use std::net::TcpStream; use std::time::Duration; let stream = TcpStream::connect("127.0.0.1:8080") .expect("Couldn't connect to the server..."); stream.set_linger(Some(Duration::from_secs(0))).expect("set_linger should succeed");fn linger(&self) -> Result<Option<Duration>>Gets the value of the
SO_LINGERoption on this socket.For more information about this option, see
TcpStream::set_linger.Examples
#![feature(tcp_linger)] use std::net::TcpStream; use std::time::Duration; let stream = TcpStream::connect("127.0.0.1:8080") .expect("Couldn't connect to the server..."); stream.set_linger(Some(Duration::from_secs(0))).expect("set_linger should succeed"); assert_eq!(stream.linger().unwrap(), Some(Duration::from_secs(0)));fn set_keepalive(&self, keepalive: bool) -> Result<()>Sets the value of the
SO_KEEPALIVEoption on this socket.If set to
true, the operating system will periodically send keepalive probes on an idle connection to verify that the remote peer is still reachable. If the peer fails to respond after a system-determined number of probes, the connection is considered broken and subsequent I/O calls will return an error.This is useful for detecting dead peers on long-lived connections where no application-level traffic is exchanged, such as database or SSH connections.
The timing and frequency of keepalive probes are controlled by system-level settings and are not configured by this method alone.
Examples
#![feature(tcp_keepalive)] use std::net::TcpStream; let stream = TcpStream::connect("127.0.0.1:8080") .expect("Couldn't connect to the server..."); stream.set_keepalive(true).expect("set_keepalive should succeed");fn keepalive(&self) -> Result<bool>Gets the value of the
SO_KEEPALIVEoption on this socket.For more information about this option, see
TcpStream::set_keepalive.Examples
#![feature(tcp_keepalive)] use std::net::TcpStream; let stream = TcpStream::connect("127.0.0.1:8080") .expect("Couldn't connect to the server..."); stream.set_keepalive(true).expect("set_keepalive should succeed"); assert_eq!(stream.keepalive().unwrap_or(false), true);fn set_nodelay(&self, nodelay: bool) -> Result<()>Sets the value of the
TCP_NODELAYoption on this socket.If set, this option disables the Nagle algorithm. This means that segments are always sent as soon as possible, even if there is only a small amount of data. When not set, data is buffered until there is a sufficient amount to send out, thereby avoiding the frequent sending of small packets.
Examples
use std::net::TcpStream; let stream = TcpStream::connect("127.0.0.1:8080") .expect("Couldn't connect to the server..."); stream.set_nodelay(true).expect("set_nodelay should succeed");fn nodelay(&self) -> Result<bool>Gets the value of the
TCP_NODELAYoption on this socket.For more information about this option, see
TcpStream::set_nodelay.Examples
use std::net::TcpStream; let stream = TcpStream::connect("127.0.0.1:8080") .expect("Couldn't connect to the server..."); stream.set_nodelay(true).expect("set_nodelay should succeed"); assert_eq!(stream.nodelay().unwrap_or(false), true);fn set_ttl(&self, ttl: u32) -> Result<()>Sets the value for the
IP_TTLoption on this socket.This value sets the time-to-live field that is used in every packet sent from this socket.
Examples
use std::net::TcpStream; let stream = TcpStream::connect("127.0.0.1:8080") .expect("Couldn't connect to the server..."); stream.set_ttl(100).expect("set_ttl should succeed");fn ttl(&self) -> Result<u32>Gets the value of the
IP_TTLoption for this socket.For more information about this option, see
TcpStream::set_ttl.Examples
use std::net::TcpStream; let stream = TcpStream::connect("127.0.0.1:8080") .expect("Couldn't connect to the server..."); stream.set_ttl(100).expect("set_ttl should succeed"); assert_eq!(stream.ttl().unwrap_or(0), 100);fn take_error(&self) -> Result<Option<Error>>Gets the value of the
SO_ERRORoption on this socket.This will retrieve the stored error in the underlying socket, clearing the field in the process. This can be useful for checking errors between calls.
Examples
use std::net::TcpStream; let stream = TcpStream::connect("127.0.0.1:8080") .expect("Couldn't connect to the server..."); stream.take_error().expect("No error was expected...");fn set_nonblocking(&self, nonblocking: bool) -> Result<()>Moves this TCP stream into or out of nonblocking mode.
This will result in
read,write,recvandsendsystem operations becoming nonblocking, i.e., immediately returning from their calls. If the IO operation is successful,Okis returned and no further action is required. If the IO operation could not be completed and needs to be retried, an error with kindio::ErrorKind::WouldBlockis returned.On most Unix platforms, calling this method corresponds to calling
ioctlFIONBIO. On Windows, calling this method corresponds to callingioctlsocketFIONBIO.Examples
Reading bytes from a TCP stream in non-blocking mode:
use std::io::{self, Read}; use std::net::TcpStream; let mut stream = TcpStream::connect("127.0.0.1:7878") .expect("Couldn't connect to the server..."); stream.set_nonblocking(true).expect("set_nonblocking should succeed"); # fn wait_for_fd() { unimplemented!() } let mut buf = vec![]; loop { match stream.read_to_end(&mut buf) { Ok(_) => break, Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => { // wait until network socket is ready, typically implemented // via platform-specific APIs such as epoll or IOCP wait_for_fd(); } Err(e) => panic!("encountered IO error: {e}"), }; }; println!("bytes: {buf:?}");
Trait Implementations
impl AsFd for TcpStream
fn as_fd(&self) -> BorrowedFd<'_>
impl AsInner<TcpStream> for TcpStream
fn as_inner(&self) -> &TcpStream
impl AsRawFd for TcpStream
fn as_raw_fd(&self) -> RawFd
impl AsRawSocket for TcpStream
fn as_raw_socket(&self) -> RawSocket
impl AsSocket for TcpStream
fn as_socket(&self) -> BorrowedSocket<'_>
impl CopyRead for TcpStream
fn properties(&self) -> CopyParams
impl CopyWrite for TcpStream
fn properties(&self) -> CopyParams
impl Debug for TcpStream
fn fmt(&self, f: &mut Formatter<'_>) -> Result
impl From<OwnedFd> for TcpStream
fn from(owned_fd: OwnedFd) -> Self
impl From<OwnedSocket> for TcpStream
fn from(owned: OwnedSocket) -> Self
impl FromInner<TcpStream> for TcpStream
fn from_inner(inner: TcpStream) -> TcpStream
impl FromRawFd for TcpStream
unsafe fn from_raw_fd(fd: RawFd) -> TcpStream
impl FromRawSocket for TcpStream
unsafe fn from_raw_socket(sock: RawSocket) -> TcpStream
impl IntoInner<TcpStream> for TcpStream
fn into_inner(self) -> TcpStream
impl IntoRawFd for TcpStream
fn into_raw_fd(self) -> RawFd
impl IntoRawSocket for TcpStream
fn into_raw_socket(self) -> RawSocket
impl Read for TcpStream
fn read(&mut self, buf: &mut [u8]) -> Result<usize>fn read_buf(&mut self, buf: BorrowedCursor<'_, u8>) -> Result<()>fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize>fn is_read_vectored(&self) -> bool
impl SpecCopy for TcpStream
fn copy<R: Read + ?Sized, W: Write + ?Sized>(read: &mut R, write: &mut W) -> Result<CopyState>
impl TcpStreamExt for TcpStream
fn set_quickack(&self, quickack: bool) -> Result<()>fn quickack(&self) -> Result<bool>fn set_deferaccept(&self, accept: Duration) -> Result<()>fn deferaccept(&self) -> Result<Duration>
impl Write for TcpStream
fn write(&mut self, buf: &[u8]) -> Result<usize>fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize>fn is_write_vectored(&self) -> boolfn flush(&mut self) -> Result<()>
Auto Trait Implementations
impl Freeze for TcpStream
impl RefUnwindSafe for TcpStream
impl Send for TcpStream
impl Sync for TcpStream
impl Unpin for TcpStream
impl UnsafeUnpin for TcpStream
impl UnwindSafe for TcpStream
Blanket Implementations
impl<R> SpecReadByte for TcpStream
where
R: Read,
fn spec_read_byte(&mut self) -> Option<Result<u8, Error>>
impl<T> Any for TcpStream
where
T: 'static + ?Sized,
fn type_id(&self) -> TypeId
impl<T> Borrow<T> for TcpStream
where
T: ?Sized,
fn borrow(&self) -> &T
impl<T> BorrowMut<T> for TcpStream
where
T: ?Sized,
fn borrow_mut(&mut self) -> &mut T
impl<T> From<T> for TcpStream
fn from(t: T) -> TReturns the argument unchanged.
impl<T> SizeHint for TcpStream
where
T: ?Sized,
fn lower_bound(&self) -> usizefn upper_bound(&self) -> Option<usize>
impl<T> SizedTypeProperties for TcpStream
impl<T, U> Into<U> for TcpStream
where
U: From<T>,
fn into(self) -> UCalls
U::from(self).That is, this conversion is whatever the implementation of
[From]<T> for Uchooses to do.
impl<T, U> TryFrom<U> for TcpStream
where
U: Into<T>,
type Error = Infallible;fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
impl<T, U> TryInto<U> for TcpStream
where
U: TryFrom<T>,
type Error = <U as TryFrom<T>>::Error;fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>