pub struct TcpStream(/* private fields */);Expand description
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.
Implementationsยง
Sourceยงimpl TcpStream
impl TcpStream
1.0.0 ยท Sourcepub fn connect<A: ToSocketAddrs>(addr: A) -> Result<TcpStream>
pub fn connect<A: ToSocketAddrs>(addr: A) -> Result<TcpStream>
Opens a TCP connection to a remote host.
addr is an address of the remote host. Anything which implements
ToSocketAddrs trait can be supplied for the address; see this trait
documentation for concrete examples.
If addr yields multiple addresses, connect will 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 to 127.0.0.1:8081:
1.21.0 ยท Sourcepub fn connect_timeout(
addr: &SocketAddr,
timeout: Duration,
) -> Result<TcpStream>
pub fn connect_timeout( addr: &SocketAddr, timeout: Duration, ) -> Result<TcpStream>
Opens a TCP connection to a remote host with a timeout.
Unlike connect, connect_timeout takes a single SocketAddr since
timeout must be applied to individual addresses.
It is an error to pass a zero Duration to this function.
Unlike other methods on TcpStream, this does not correspond to a
single system call. It instead calls connect in nonblocking mode and
then uses an OS-specific mechanism to await the completion of the
connection request.
1.0.0 ยท Sourcepub fn peer_addr(&self) -> Result<SocketAddr>
pub fn peer_addr(&self) -> Result<SocketAddr>
Returns the socket address of the remote peer of this TCP connection.
ยงExamples
1.0.0 ยท Sourcepub fn local_addr(&self) -> Result<SocketAddr>
pub fn local_addr(&self) -> Result<SocketAddr>
Returns the socket address of the local half of this TCP connection.
ยงExamples
1.0.0 ยท Sourcepub fn shutdown(&self, how: Shutdown) -> Result<()>
pub 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 return ErrorKind::NotConnected.
This may change in the future.
ยงExamples
1.0.0 ยท Sourcepub fn try_clone(&self) -> Result<TcpStream>
pub fn try_clone(&self) -> Result<TcpStream>
Creates a new independently owned handle to the underlying socket.
The returned TcpStream is 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
1.4.0 ยท Sourcepub fn set_read_timeout(&self, dur: Option<Duration>) -> Result<()>
pub fn set_read_timeout(&self, dur: Option<Duration>) -> Result<()>
Sets the read timeout to the timeout specified.
If the value specified is None, then read calls will block
indefinitely. An Err is returned if the zero Duration is
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 return TimedOut.
ยง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 Err is returned if the zero Duration is passed to this
method:
1.4.0 ยท Sourcepub fn set_write_timeout(&self, dur: Option<Duration>) -> Result<()>
pub fn set_write_timeout(&self, dur: Option<Duration>) -> Result<()>
Sets the write timeout to the timeout specified.
If the value specified is None, then write calls will block
indefinitely. An Err is returned if the zero Duration is
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 return TimedOut.
ยง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 Err is returned if the zero Duration is passed to this
method:
1.4.0 ยท Sourcepub fn read_timeout(&self) -> Result<Option<Duration>>
pub fn read_timeout(&self) -> Result<Option<Duration>>
1.4.0 ยท Sourcepub fn write_timeout(&self) -> Result<Option<Duration>>
pub fn write_timeout(&self) -> Result<Option<Duration>>
1.18.0 ยท Sourcepub fn peek(&self, buf: &mut [u8]) -> Result<usize>
pub 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_PEEK as a flag to the underlying recv system call.
ยงExamples
Sourcepub fn set_linger(&self, linger: Option<Duration>) -> Result<()>
๐ฌThis is a nightly-only experimental API. (tcp_linger #88494)
pub fn set_linger(&self, linger: Option<Duration>) -> Result<()>
tcp_linger #88494)Sets the value of the SO_LINGER option on this socket.
This value controls how the socket is closed when data remains
to be sent. If SO_LINGER is 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
Sourcepub fn linger(&self) -> Result<Option<Duration>>
๐ฌThis is a nightly-only experimental API. (tcp_linger #88494)
pub fn linger(&self) -> Result<Option<Duration>>
tcp_linger #88494)Gets the value of the SO_LINGER option 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)));Sourcepub fn set_keepalive(&self, keepalive: bool) -> Result<()>
๐ฌThis is a nightly-only experimental API. (tcp_keepalive #155889)
pub fn set_keepalive(&self, keepalive: bool) -> Result<()>
tcp_keepalive #155889)Sets the value of the SO_KEEPALIVE option 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
Sourcepub fn keepalive(&self) -> Result<bool>
๐ฌThis is a nightly-only experimental API. (tcp_keepalive #155889)
pub fn keepalive(&self) -> Result<bool>
tcp_keepalive #155889)Gets the value of the SO_KEEPALIVE option on this socket.
For more information about this option, see TcpStream::set_keepalive.
ยงExamples
1.9.0 ยท Sourcepub fn set_nodelay(&self, nodelay: bool) -> Result<()>
pub fn set_nodelay(&self, nodelay: bool) -> Result<()>
Sets the value of the TCP_NODELAY option 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
1.9.0 ยท Sourcepub fn nodelay(&self) -> Result<bool>
pub fn nodelay(&self) -> Result<bool>
Gets the value of the TCP_NODELAY option on this socket.
For more information about this option, see TcpStream::set_nodelay.
ยงExamples
1.9.0 ยท Sourcepub fn set_ttl(&self, ttl: u32) -> Result<()>
pub fn set_ttl(&self, ttl: u32) -> Result<()>
Sets the value for the IP_TTL option on this socket.
This value sets the time-to-live field that is used in every packet sent from this socket.
ยงExamples
1.9.0 ยท Sourcepub fn ttl(&self) -> Result<u32>
pub fn ttl(&self) -> Result<u32>
Gets the value of the IP_TTL option for this socket.
For more information about this option, see TcpStream::set_ttl.
ยงExamples
1.9.0 ยท Sourcepub fn take_error(&self) -> Result<Option<Error>>
pub fn take_error(&self) -> Result<Option<Error>>
Gets the value of the SO_ERROR option 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
1.9.0 ยท Sourcepub fn set_nonblocking(&self, nonblocking: bool) -> Result<()>
pub fn set_nonblocking(&self, nonblocking: bool) -> Result<()>
Moves this TCP stream into or out of nonblocking mode.
This will result in read, write, recv and send system operations
becoming nonblocking, i.e., immediately returning from their calls.
If the IO operation is successful, Ok is returned and no further
action is required. If the IO operation could not be completed and needs
to be retried, an error with kind io::ErrorKind::WouldBlock is
returned.
On most Unix platforms, calling this method corresponds to calling ioctl
FIONBIO. On Windows, calling this method corresponds to calling
ioctlsocket FIONBIO.
ยง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");
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ยง
1.63.0 ยท Sourceยงimpl AsFd for TcpStream
Available on (Hermit or Motor OS or Trusty or Unix or WASI) and non-Trusty only.
impl AsFd for TcpStream
Sourceยงfn as_fd(&self) -> BorrowedFd<'_>
fn as_fd(&self) -> BorrowedFd<'_>
1.0.0 ยท Sourceยงimpl AsRawFd for TcpStream
Available on (Hermit or Motor OS or Trusty or Unix or WASI) and non-Trusty only.
impl AsRawFd for TcpStream
1.0.0 ยท Sourceยงimpl AsRawSocket for TcpStream
Available on Windows only.
impl AsRawSocket for TcpStream
Sourceยงfn as_raw_socket(&self) -> RawSocket
fn as_raw_socket(&self) -> RawSocket
1.63.0 ยท Sourceยงimpl AsSocket for TcpStream
Available on Windows only.
impl AsSocket for TcpStream
Sourceยงfn as_socket(&self) -> BorrowedSocket<'_>
fn as_socket(&self) -> BorrowedSocket<'_>
1.63.0 ยท Sourceยงimpl From<OwnedFd> for TcpStream
Available on (Hermit or Motor OS or Trusty or Unix or WASI) and non-Trusty only.
impl From<OwnedFd> for TcpStream
1.63.0 ยท Sourceยงimpl From<OwnedSocket> for TcpStream
Available on Windows only.
impl From<OwnedSocket> for TcpStream
Sourceยงfn from(owned: OwnedSocket) -> Self
fn from(owned: OwnedSocket) -> Self
1.63.0 ยท Sourceยงimpl From<TcpStream> for OwnedSocket
Available on Windows only.
impl From<TcpStream> for OwnedSocket
1.63.0 ยท Sourceยงimpl From<TcpStream> for OwnedFd
Available on (Hermit or Motor OS or Trusty or Unix or WASI) and non-Trusty only.
impl From<TcpStream> for OwnedFd
1.1.0 ยท Sourceยงimpl FromRawFd for TcpStream
Available on (Hermit or Motor OS or Trusty or Unix or WASI) and non-Trusty only.
impl FromRawFd for TcpStream
1.1.0 ยท Sourceยงimpl FromRawSocket for TcpStream
Available on Windows only.
impl FromRawSocket for TcpStream
1.4.0 ยท Sourceยงimpl IntoRawFd for TcpStream
Available on (Hermit or Motor OS or Trusty or Unix or WASI) and non-Trusty only.
impl IntoRawFd for TcpStream
Sourceยงfn into_raw_fd(self) -> RawFd
fn into_raw_fd(self) -> RawFd
1.4.0 ยท Sourceยงimpl IntoRawSocket for TcpStream
Available on Windows only.
impl IntoRawSocket for TcpStream
Sourceยงfn into_raw_socket(self) -> RawSocket
fn into_raw_socket(self) -> RawSocket
1.0.0 ยท Sourceยงimpl Read for TcpStream
impl Read for TcpStream
Sourceยงfn read(&mut self, buf: &mut [u8]) -> Result<usize>
fn read(&mut self, buf: &mut [u8]) -> Result<usize>
Sourceยงfn read_buf(&mut self, buf: BorrowedCursor<'_, u8>) -> Result<()>
fn read_buf(&mut self, buf: BorrowedCursor<'_, u8>) -> Result<()>
read_buf #78485)Sourceยงfn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize>
fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize>
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 #69941)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_exact(
&mut self,
cursor: BorrowedCursor<'_, u8>,
) -> Result<(), Error>
fn read_buf_exact( &mut self, cursor: BorrowedCursor<'_, u8>, ) -> Result<(), Error>
read_buf #78485)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 #148848)1.0.0 ยท Sourceยงimpl Read for &TcpStream
impl Read for &TcpStream
Sourceยงfn read(&mut self, buf: &mut [u8]) -> Result<usize>
fn read(&mut self, buf: &mut [u8]) -> Result<usize>
Sourceยงfn read_buf(&mut self, buf: BorrowedCursor<'_, u8>) -> Result<()>
fn read_buf(&mut self, buf: BorrowedCursor<'_, u8>) -> Result<()>
read_buf #78485)Sourceยงfn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize>
fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize>
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 #69941)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_exact(
&mut self,
cursor: BorrowedCursor<'_, u8>,
) -> Result<(), Error>
fn read_buf_exact( &mut self, cursor: BorrowedCursor<'_, u8>, ) -> Result<(), Error>
read_buf #78485)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 #148848)1.89.0 ยท Sourceยงimpl TcpStreamExt for TcpStream
Available on Android or Cygwin or Linux only.
impl TcpStreamExt for TcpStream
Sourceยงfn set_quickack(&self, quickack: bool) -> Result<()>
fn set_quickack(&self, quickack: bool) -> Result<()>
TCP_QUICKACK. Read moreSourceยงfn quickack(&self) -> Result<bool>
fn quickack(&self) -> Result<bool>
TCP_QUICKACK option on this socket. Read more1.0.0 ยท Sourceยงimpl Write for TcpStream
impl Write for TcpStream
Sourceยงfn write(&mut self, buf: &[u8]) -> Result<usize>
fn write(&mut self, buf: &[u8]) -> Result<usize>
Sourceยงfn is_write_vectored(&self) -> bool
fn is_write_vectored(&self) -> bool
can_vector #69941)Sourceยงfn flush(&mut self) -> Result<()>
fn flush(&mut self) -> Result<()>
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 #70436)1.0.0 ยท Sourceยงimpl Write for &TcpStream
impl Write for &TcpStream
Sourceยงfn write(&mut self, buf: &[u8]) -> Result<usize>
fn write(&mut self, buf: &[u8]) -> Result<usize>
Sourceยงfn is_write_vectored(&self) -> bool
fn is_write_vectored(&self) -> bool
can_vector #69941)Sourceยงfn flush(&mut self) -> Result<()>
fn flush(&mut self) -> Result<()>
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 #70436)