pub struct TcpStream(/* private fields */);Expand description
A TCP stream between a local and a remote socket.
After creating aTcpStream by eitherconnecting to a remote host oraccepting a connection on aTcpListener, data can be transmittedbyreading andwriting to it.
The connection will be closed when the value is dropped. The reading and writingportions of the connection can also be shut down individually with theshutdownmethod.
The Transmission Control Protocol is specified inIETF RFC 793.
§Examples
usestd::io::prelude::*;usestd::net::TcpStream;fnmain() -> std::io::Result<()> {letmutstream = 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 inSOCK_STREAM mode are made withMSG_NOSIGNAL flag. This suppresses the emission of theSIGPIPE signal when writingto disconnected socket. In some cases, getting aSIGPIPE would trigger process termination.
Implementations§
Source§implTcpStream
implTcpStream
1.0.0 ·Sourcepub fnconnect<A:ToSocketAddrs>(addr: A) ->Result<TcpStream>
pub fnconnect<A:ToSocketAddrs>(addr: A) ->Result<TcpStream>
Opens a TCP connection to a remote host.
addr is an address of the remote host. Anything which implementsToSocketAddrs trait can be supplied for the address; see this traitdocumentation for concrete examples.
Ifaddr yields multiple addresses,connect will be attempted witheach of the addresses until a connection is successful. If none ofthe addresses result in a successful connection, the error returned fromthe last connection attempt (the last address) is returned.
§Examples
Open a TCP connection to127.0.0.1:8080:
usestd::net::TcpStream;if letOk(stream) = TcpStream::connect("127.0.0.1:8080") {println!("Connected to the server!");}else{println!("Couldn't connect to server...");}Open a TCP connection to127.0.0.1:8080. If the connection fails, opena TCP connection to127.0.0.1:8081:
1.21.0 ·Sourcepub fnconnect_timeout( addr: &SocketAddr, timeout:Duration,) ->Result<TcpStream>
pub fnconnect_timeout( addr: &SocketAddr, timeout:Duration,) ->Result<TcpStream>
Opens a TCP connection to a remote host with a timeout.
Unlikeconnect,connect_timeout takes a singleSocketAddr sincetimeout must be applied to individual addresses.
It is an error to pass a zeroDuration to this function.
Unlike other methods onTcpStream, this does not correspond to asingle system call. It instead callsconnect in nonblocking mode andthen uses an OS-specific mechanism to await the completion of theconnection request.
1.0.0 ·Sourcepub fnpeer_addr(&self) ->Result<SocketAddr>
pub fnpeer_addr(&self) ->Result<SocketAddr>
Returns the socket address of the remote peer of this TCP connection.
§Examples
1.0.0 ·Sourcepub fnlocal_addr(&self) ->Result<SocketAddr>
pub fnlocal_addr(&self) ->Result<SocketAddr>
Returns the socket address of the local half of this TCP connection.
§Examples
1.0.0 ·Sourcepub fnshutdown(&self, how:Shutdown) ->Result<()>
pub fnshutdown(&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 specifiedportions to return immediately with an appropriate value (see thedocumentation ofShutdown).
§Platform-specific behavior
Calling this function multiple times may result in different behavior,depending on the operating system. On Linux, the second call willreturnOk(()), but on macOS, it will returnErrorKind::NotConnected.This may change in the future.
§Examples
1.0.0 ·Sourcepub fntry_clone(&self) ->Result<TcpStream>
pub fntry_clone(&self) ->Result<TcpStream>
Creates a new independently owned handle to the underlying socket.
The returnedTcpStream is a reference to the same stream that thisobject references. Both handles will read and write the same stream ofdata, and options set on one stream will be propagated to the otherstream.
§Examples
1.4.0 ·Sourcepub fnset_read_timeout(&self, dur:Option<Duration>) ->Result<()>
pub fnset_read_timeout(&self, dur:Option<Duration>) ->Result<()>
Sets the read timeout to the timeout specified.
If the value specified isNone, thenread calls will blockindefinitely. AnErr is returned if the zeroDuration ispassed to this method.
§Platform-specific behavior
Platforms may return a different error code whenever a read times out asa result of setting this option. For example Unix typically returns anerror of the kindWouldBlock, but Windows may returnTimedOut.
§Examples
usestd::net::TcpStream;letstream = TcpStream::connect("127.0.0.1:8080") .expect("Couldn't connect to the server...");stream.set_read_timeout(None).expect("set_read_timeout call failed");AnErr is returned if the zeroDuration is passed to thismethod:
1.4.0 ·Sourcepub fnset_write_timeout(&self, dur:Option<Duration>) ->Result<()>
pub fnset_write_timeout(&self, dur:Option<Duration>) ->Result<()>
Sets the write timeout to the timeout specified.
If the value specified isNone, thenwrite calls will blockindefinitely. AnErr is returned if the zeroDuration ispassed to this method.
§Platform-specific behavior
Platforms may return a different error code whenever a write times outas a result of setting this option. For example Unix typically returnsan error of the kindWouldBlock, but Windows may returnTimedOut.
§Examples
usestd::net::TcpStream;letstream = TcpStream::connect("127.0.0.1:8080") .expect("Couldn't connect to the server...");stream.set_write_timeout(None).expect("set_write_timeout call failed");AnErr is returned if the zeroDuration is passed to thismethod:
1.4.0 ·Sourcepub fnread_timeout(&self) ->Result<Option<Duration>>
pub fnread_timeout(&self) ->Result<Option<Duration>>
1.4.0 ·Sourcepub fnwrite_timeout(&self) ->Result<Option<Duration>>
pub fnwrite_timeout(&self) ->Result<Option<Duration>>
1.18.0 ·Sourcepub fnpeek(&self, buf: &mut [u8]) ->Result<usize>
pub fnpeek(&self, buf: &mut [u8]) ->Result<usize>
Receives data on the socket from the remote address to which it isconnected, 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 passingMSG_PEEK as a flag to the underlyingrecv system call.
§Examples
Sourcepub fnset_linger(&self, linger:Option<Duration>) ->Result<()>
🔬This is a nightly-only experimental API. (tcp_linger #88494)
pub fnset_linger(&self, linger:Option<Duration>) ->Result<()>
tcp_linger #88494)Sets the value of theSO_LINGER option on this socket.
This value controls how the socket is closed when data remainsto be sent. IfSO_LINGER is set, the socket will remain openfor the specified duration as the system attempts to send pending data.Otherwise, the system may close the socket immediately, or wait for adefault timeout.
§Examples
Sourcepub fnlinger(&self) ->Result<Option<Duration>>
🔬This is a nightly-only experimental API. (tcp_linger #88494)
pub fnlinger(&self) ->Result<Option<Duration>>
tcp_linger #88494)Gets the value of theSO_LINGER option on this socket.
For more information about this option, seeTcpStream::set_linger.
§Examples
#![feature(tcp_linger)]usestd::net::TcpStream;usestd::time::Duration;letstream = 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 call failed");assert_eq!(stream.linger().unwrap(),Some(Duration::from_secs(0)));1.9.0 ·Sourcepub fnset_nodelay(&self, nodelay:bool) ->Result<()>
pub fnset_nodelay(&self, nodelay:bool) ->Result<()>
Sets the value of theTCP_NODELAY option on this socket.
If set, this option disables the Nagle algorithm. This means thatsegments are always sent as soon as possible, even if there is only asmall amount of data. When not set, data is buffered until there is asufficient amount to send out, thereby avoiding the frequent sending ofsmall packets.
§Examples
1.9.0 ·Sourcepub fnnodelay(&self) ->Result<bool>
pub fnnodelay(&self) ->Result<bool>
Gets the value of theTCP_NODELAY option on this socket.
For more information about this option, seeTcpStream::set_nodelay.
§Examples
1.9.0 ·Sourcepub fnset_ttl(&self, ttl:u32) ->Result<()>
pub fnset_ttl(&self, ttl:u32) ->Result<()>
Sets the value for theIP_TTL option on this socket.
This value sets the time-to-live field that is used in every packet sentfrom this socket.
§Examples
1.9.0 ·Sourcepub fnttl(&self) ->Result<u32>
pub fnttl(&self) ->Result<u32>
Gets the value of theIP_TTL option for this socket.
For more information about this option, seeTcpStream::set_ttl.
§Examples
1.9.0 ·Sourcepub fntake_error(&self) ->Result<Option<Error>>
pub fntake_error(&self) ->Result<Option<Error>>
Gets the value of theSO_ERROR option on this socket.
This will retrieve the stored error in the underlying socket, clearingthe field in the process. This can be useful for checking errors betweencalls.
§Examples
1.9.0 ·Sourcepub fnset_nonblocking(&self, nonblocking:bool) ->Result<()>
pub fnset_nonblocking(&self, nonblocking:bool) ->Result<()>
Moves this TCP stream into or out of nonblocking mode.
This will result inread,write,recv andsend system operationsbecoming nonblocking, i.e., immediately returning from their calls.If the IO operation is successful,Ok is returned and no furtheraction is required. If the IO operation could not be completed and needsto be retried, an error with kindio::ErrorKind::WouldBlock isreturned.
On Unix platforms, calling this method corresponds to callingfcntlFIONBIO. On Windows calling this method corresponds to callingioctlsocketFIONBIO.
§Examples
Reading bytes from a TCP stream in non-blocking mode:
usestd::io::{self, Read};usestd::net::TcpStream;letmutstream = TcpStream::connect("127.0.0.1:7878") .expect("Couldn't connect to the server...");stream.set_nonblocking(true).expect("set_nonblocking call failed");letmutbuf =vec![];loop{matchstream.read_to_end(&mutbuf) {Ok(_) =>break,Err(refe)ife.kind() == io::ErrorKind::WouldBlock => {// wait until network socket is ready, typically implemented // via platform-specific APIs such as epoll or IOCPwait_for_fd(); }Err(e) =>panic!("encountered IO error: {e}"), };};println!("bytes: {buf:?}");Trait Implementations§
1.63.0 ·Source§implAsFd forTcpStream
Available on(Unix or HermitCore ortarget_os=trusty or WASI ortarget_os=motor) and non-target_os=trusty only.
implAsFd forTcpStream
target_os=trusty or WASI ortarget_os=motor) and non-target_os=trusty only.Source§fnas_fd(&self) ->BorrowedFd<'_>
fnas_fd(&self) ->BorrowedFd<'_>
1.0.0 ·Source§implAsRawFd forTcpStream
Available onnon-target_os=trusty and (Unix or HermitCore ortarget_os=trusty or WASI ortarget_os=motor) only.
implAsRawFd forTcpStream
target_os=trusty and (Unix or HermitCore ortarget_os=trusty or WASI ortarget_os=motor) only.1.0.0 ·Source§implAsRawSocket forTcpStream
Available onWindows only.
implAsRawSocket forTcpStream
Source§fnas_raw_socket(&self) ->RawSocket
fnas_raw_socket(&self) ->RawSocket
1.63.0 ·Source§implAsSocket forTcpStream
Available onWindows only.
implAsSocket forTcpStream
Source§fnas_socket(&self) ->BorrowedSocket<'_>
fnas_socket(&self) ->BorrowedSocket<'_>
1.63.0 ·Source§implFrom<OwnedFd> forTcpStream
Available on(Unix or HermitCore ortarget_os=trusty or WASI ortarget_os=motor) and non-target_os=trusty only.
implFrom<OwnedFd> forTcpStream
target_os=trusty or WASI ortarget_os=motor) and non-target_os=trusty only.1.63.0 ·Source§implFrom<OwnedSocket> forTcpStream
Available onWindows only.
implFrom<OwnedSocket> forTcpStream
Source§fnfrom(owned:OwnedSocket) -> Self
fnfrom(owned:OwnedSocket) -> Self
1.63.0 ·Source§implFrom<TcpStream> forOwnedFd
Available on(Unix or HermitCore ortarget_os=trusty or WASI ortarget_os=motor) and non-target_os=trusty only.
implFrom<TcpStream> forOwnedFd
target_os=trusty or WASI ortarget_os=motor) and non-target_os=trusty only.1.63.0 ·Source§implFrom<TcpStream> forOwnedSocket
Available onWindows only.
implFrom<TcpStream> forOwnedSocket
1.1.0 ·Source§implFromRawFd forTcpStream
Available onnon-target_os=trusty and (Unix or HermitCore ortarget_os=trusty or WASI ortarget_os=motor) only.
implFromRawFd forTcpStream
target_os=trusty and (Unix or HermitCore ortarget_os=trusty or WASI ortarget_os=motor) only.1.1.0 ·Source§implFromRawSocket forTcpStream
Available onWindows only.
implFromRawSocket forTcpStream
1.4.0 ·Source§implIntoRawFd forTcpStream
Available onnon-target_os=trusty and (Unix or HermitCore ortarget_os=trusty or WASI ortarget_os=motor) only.
implIntoRawFd forTcpStream
target_os=trusty and (Unix or HermitCore ortarget_os=trusty or WASI ortarget_os=motor) only.Source§fninto_raw_fd(self) ->RawFd
fninto_raw_fd(self) ->RawFd
1.4.0 ·Source§implIntoRawSocket forTcpStream
Available onWindows only.
implIntoRawSocket forTcpStream
Source§fninto_raw_socket(self) ->RawSocket
fninto_raw_socket(self) ->RawSocket
1.0.0 ·Source§implRead for &TcpStream
implRead for &TcpStream
Source§fnread(&mut self, buf: &mut [u8]) ->Result<usize>
fnread(&mut self, buf: &mut [u8]) ->Result<usize>
Source§fnread_buf(&mut self, buf:BorrowedCursor<'_>) ->Result<()>
fnread_buf(&mut self, buf:BorrowedCursor<'_>) ->Result<()>
read_buf #78485)Source§fnread_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) ->Result<usize>
fnread_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) ->Result<usize>
read, except that it reads into a slice of buffers.Read moreSource§fnis_read_vectored(&self) ->bool
fnis_read_vectored(&self) ->bool
can_vector #69941)1.0.0 ·Source§fnread_to_end(&mut self, buf: &mutVec<u8>) ->Result<usize>
fnread_to_end(&mut self, buf: &mutVec<u8>) ->Result<usize>
buf.Read more1.0.0 ·Source§fnread_to_string(&mut self, buf: &mutString) ->Result<usize>
fnread_to_string(&mut self, buf: &mutString) ->Result<usize>
buf.Read more1.6.0 ·Source§fnread_exact(&mut self, buf: &mut [u8]) ->Result<()>
fnread_exact(&mut self, buf: &mut [u8]) ->Result<()>
buf.Read moreSource§fnread_buf_exact(&mut self, cursor:BorrowedCursor<'_>) ->Result<()>
fnread_buf_exact(&mut self, cursor:BorrowedCursor<'_>) ->Result<()>
read_buf #78485)cursor.Read more1.0.0 ·Source§fnby_ref(&mut self) -> &mut Selfwhere Self:Sized,
fnby_ref(&mut self) -> &mut Selfwhere Self:Sized,
Read.Read more1.0.0 ·Source§fnchain<R:Read>(self, next: R) ->Chain<Self, R>ⓘwhere Self:Sized,
fnchain<R:Read>(self, next: R) ->Chain<Self, R>ⓘwhere Self:Sized,
1.0.0 ·Source§implRead forTcpStream
implRead forTcpStream
Source§fnread(&mut self, buf: &mut [u8]) ->Result<usize>
fnread(&mut self, buf: &mut [u8]) ->Result<usize>
Source§fnread_buf(&mut self, buf:BorrowedCursor<'_>) ->Result<()>
fnread_buf(&mut self, buf:BorrowedCursor<'_>) ->Result<()>
read_buf #78485)Source§fnread_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) ->Result<usize>
fnread_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) ->Result<usize>
read, except that it reads into a slice of buffers.Read moreSource§fnis_read_vectored(&self) ->bool
fnis_read_vectored(&self) ->bool
can_vector #69941)1.0.0 ·Source§fnread_to_end(&mut self, buf: &mutVec<u8>) ->Result<usize>
fnread_to_end(&mut self, buf: &mutVec<u8>) ->Result<usize>
buf.Read more1.0.0 ·Source§fnread_to_string(&mut self, buf: &mutString) ->Result<usize>
fnread_to_string(&mut self, buf: &mutString) ->Result<usize>
buf.Read more1.6.0 ·Source§fnread_exact(&mut self, buf: &mut [u8]) ->Result<()>
fnread_exact(&mut self, buf: &mut [u8]) ->Result<()>
buf.Read moreSource§fnread_buf_exact(&mut self, cursor:BorrowedCursor<'_>) ->Result<()>
fnread_buf_exact(&mut self, cursor:BorrowedCursor<'_>) ->Result<()>
read_buf #78485)cursor.Read more1.0.0 ·Source§fnby_ref(&mut self) -> &mut Selfwhere Self:Sized,
fnby_ref(&mut self) -> &mut Selfwhere Self:Sized,
Read.Read more1.0.0 ·Source§fnchain<R:Read>(self, next: R) ->Chain<Self, R>ⓘwhere Self:Sized,
fnchain<R:Read>(self, next: R) ->Chain<Self, R>ⓘwhere Self:Sized,
1.89.0 ·Source§implTcpStreamExt forTcpStream
Available onLinux or Android or Cygwin only.
implTcpStreamExt forTcpStream
Source§fnset_quickack(&self, quickack:bool) ->Result<()>
fnset_quickack(&self, quickack:bool) ->Result<()>
TCP_QUICKACK.Read moreSource§fnquickack(&self) ->Result<bool>
fnquickack(&self) ->Result<bool>
TCP_QUICKACK option on this socket.Read more1.0.0 ·Source§implWrite for &TcpStream
implWrite for &TcpStream
Source§fnwrite(&mut self, buf: &[u8]) ->Result<usize>
fnwrite(&mut self, buf: &[u8]) ->Result<usize>
Source§fnis_write_vectored(&self) ->bool
fnis_write_vectored(&self) ->bool
can_vector #69941)Source§fnflush(&mut self) ->Result<()>
fnflush(&mut self) ->Result<()>
1.0.0 ·Source§fnwrite_all(&mut self, buf: &[u8]) ->Result<()>
fnwrite_all(&mut self, buf: &[u8]) ->Result<()>
Source§fnwrite_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) ->Result<()>
fnwrite_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) ->Result<()>
write_all_vectored #70436)1.0.0 ·Source§implWrite forTcpStream
implWrite forTcpStream
Source§fnwrite(&mut self, buf: &[u8]) ->Result<usize>
fnwrite(&mut self, buf: &[u8]) ->Result<usize>
Source§fnis_write_vectored(&self) ->bool
fnis_write_vectored(&self) ->bool
can_vector #69941)Source§fnflush(&mut self) ->Result<()>
fnflush(&mut self) ->Result<()>
1.0.0 ·Source§fnwrite_all(&mut self, buf: &[u8]) ->Result<()>
fnwrite_all(&mut self, buf: &[u8]) ->Result<()>
Source§fnwrite_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) ->Result<()>
fnwrite_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) ->Result<()>
write_all_vectored #70436)