std:🥅:TcpStream - Rust (original) (raw)
Struct std::net::TcpStream1.0.0 [−] [src]
pub struct TcpStream(_);
A TCP stream between a local and a remote socket.
After creating a TcpStream
by either connecting to a remote host oraccepting 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 shutdownmethod.
The Transmission Control Protocol is specified in IETF RFC 793.
use std::io::prelude::*; use std:🥅:TcpStream;
{ let mut stream = TcpStream::connect("127.0.0.1:34254").unwrap();
let _ = stream.write(&[1]);
let _ = stream.read(&mut [0; 128]);
} Run
impl [TcpStream](../../std/net/struct.TcpStream.html "struct std:🥅:TcpStream")
[src]
pub fn [connect](#method.connect)<A: [ToSocketAddrs](../../std/net/trait.ToSocketAddrs.html "trait std:🥅:ToSocketAddrs")>(addr: A) -> [Result](../../std/io/type.Result.html "type std::io::Result")<[TcpStream](../../std/net/struct.TcpStream.html "struct std:🥅:TcpStream")>
[src]
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 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.
Open a TCP connection to 127.0.0.1:8080
:
use std:🥅:TcpStream;
if let Ok(stream) = TcpStream::connect("127.0.0.1:8080") { println!("Connected to the server!"); } else { println!("Couldn't connect to server..."); }Run
Open a TCP connection to 127.0.0.1:8080
. If the connection fails, open a TCP connection to 127.0.0.1:8081
:
use std:🥅:{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..."); }Run
`pub fn connect_timeout(
addr: &SocketAddr,
timeout: Duration
) -> Result<TcpStream>`
1.21.0
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.
pub fn [peer_addr](#method.peer%5Faddr)(&self) -> [Result](../../std/io/type.Result.html "type std::io::Result")<[SocketAddr](../../std/net/enum.SocketAddr.html "enum std:🥅:SocketAddr")>
[src]
Returns the socket address of the remote peer of this TCP connection.
use std:🥅:{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)));Run
pub fn [local_addr](#method.local%5Faddr)(&self) -> [Result](../../std/io/type.Result.html "type std::io::Result")<[SocketAddr](../../std/net/enum.SocketAddr.html "enum std:🥅:SocketAddr")>
[src]
Returns the socket address of the local half of this TCP connection.
use std:🥅:{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)));Run
pub fn [shutdown](#method.shutdown)(&self, how: [Shutdown](../../std/net/enum.Shutdown.html "enum std:🥅:Shutdown")) -> [Result](../../std/io/type.Result.html "type std::io::Result")<[()](../primitive.unit.html)>
[src]
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).
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.
use std:🥅:{Shutdown, TcpStream};
let stream = TcpStream::connect("127.0.0.1:8080") .expect("Couldn't connect to the server..."); stream.shutdown(Shutdown::Both).expect("shutdown call failed");Run
pub fn [try_clone](#method.try%5Fclone)(&self) -> [Result](../../std/io/type.Result.html "type std::io::Result")<[TcpStream](../../std/net/struct.TcpStream.html "struct std:🥅:TcpStream")>
[src]
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.
use std:🥅: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 failed...");Run
pub fn [set_read_timeout](#method.set%5Fread%5Ftimeout)(&self, dur: [Option](../../std/option/enum.Option.html "enum std::option::Option")<[Duration](../../std/time/struct.Duration.html "struct std::time::Duration")>) -> [Result](../../std/io/type.Result.html "type std::io::Result")<[()](../primitive.unit.html)>
1.4.0
Sets the read timeout to the timeout specified.
If the value specified is None, then read calls will block indefinitely. It is an error to pass the zero Duration
to this method.
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.
use std:🥅: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 call failed");Run
pub fn [set_write_timeout](#method.set%5Fwrite%5Ftimeout)(&self, dur: [Option](../../std/option/enum.Option.html "enum std::option::Option")<[Duration](../../std/time/struct.Duration.html "struct std::time::Duration")>) -> [Result](../../std/io/type.Result.html "type std::io::Result")<[()](../primitive.unit.html)>
1.4.0
Sets the write timeout to the timeout specified.
If the value specified is None, then write calls will block indefinitely. It is an error to pass the zero Duration to this method.
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.
use std:🥅: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 call failed");Run
pub fn [read_timeout](#method.read%5Ftimeout)(&self) -> [Result](../../std/io/type.Result.html "type std::io::Result")<[Option](../../std/option/enum.Option.html "enum std::option::Option")<[Duration](../../std/time/struct.Duration.html "struct std::time::Duration")>>
1.4.0
Returns the read timeout of this socket.
If the timeout is None, then read calls will block indefinitely.
Some platforms do not provide access to the current timeout.
use std:🥅: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 call failed"); assert_eq!(stream.read_timeout().unwrap(), None);Run
pub fn [write_timeout](#method.write%5Ftimeout)(&self) -> [Result](../../std/io/type.Result.html "type std::io::Result")<[Option](../../std/option/enum.Option.html "enum std::option::Option")<[Duration](../../std/time/struct.Duration.html "struct std::time::Duration")>>
1.4.0
Returns the write timeout of this socket.
If the timeout is None, then write calls will block indefinitely.
Some platforms do not provide access to the current timeout.
use std:🥅: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 call failed"); assert_eq!(stream.write_timeout().unwrap(), None);Run
pub fn [peek](#method.peek)(&self, buf: [&mut [](../primitive.slice.html)[u8](../primitive.u8.html)[]](../primitive.slice.html)) -> [Result](../../std/io/type.Result.html "type std::io::Result")<[usize](../primitive.usize.html)>
1.18.0
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 passingMSG_PEEK
as a flag to the underlying recv
system call.
use std:🥅:TcpStream;
let stream = TcpStream::connect("127.0.0.1:8000") .expect("couldn't bind to address"); let mut buf = [0; 10]; let len = stream.peek(&mut buf).expect("peek failed");Run
pub fn [set_nodelay](#method.set%5Fnodelay)(&self, nodelay: [bool](../primitive.bool.html)) -> [Result](../../std/io/type.Result.html "type std::io::Result")<[()](../primitive.unit.html)>
1.9.0
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.
use std:🥅:TcpStream;
let stream = TcpStream::connect("127.0.0.1:8080") .expect("Couldn't connect to the server..."); stream.set_nodelay(true).expect("set_nodelay call failed");Run
pub fn [nodelay](#method.nodelay)(&self) -> [Result](../../std/io/type.Result.html "type std::io::Result")<[bool](../primitive.bool.html)>
1.9.0
Gets the value of the TCP_NODELAY
option on this socket.
For more information about this option, see set_nodelay.
use std:🥅:TcpStream;
let stream = TcpStream::connect("127.0.0.1:8080") .expect("Couldn't connect to the server..."); stream.set_nodelay(true).expect("set_nodelay call failed"); assert_eq!(stream.nodelay().unwrap_or(false), true);Run
pub fn [set_ttl](#method.set%5Fttl)(&self, ttl: [u32](../primitive.u32.html)) -> [Result](../../std/io/type.Result.html "type std::io::Result")<[()](../primitive.unit.html)>
1.9.0
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.
use std:🥅:TcpStream;
let stream = TcpStream::connect("127.0.0.1:8080") .expect("Couldn't connect to the server..."); stream.set_ttl(100).expect("set_ttl call failed");Run
pub fn [ttl](#method.ttl)(&self) -> [Result](../../std/io/type.Result.html "type std::io::Result")<[u32](../primitive.u32.html)>
1.9.0
Gets the value of the IP_TTL
option for this socket.
For more information about this option, see set_ttl.
use std:🥅:TcpStream;
let stream = TcpStream::connect("127.0.0.1:8080") .expect("Couldn't connect to the server..."); stream.set_ttl(100).expect("set_ttl call failed"); assert_eq!(stream.ttl().unwrap_or(0), 100);Run
pub fn [take_error](#method.take%5Ferror)(&self) -> [Result](../../std/io/type.Result.html "type std::io::Result")<[Option](../../std/option/enum.Option.html "enum std::option::Option")<[Error](../../std/io/struct.Error.html "struct std::io::Error")>>
1.9.0
Get 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.
use std:🥅: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...");Run
pub fn [set_nonblocking](#method.set%5Fnonblocking)(&self, nonblocking: [bool](../primitive.bool.html)) -> [Result](../../std/io/type.Result.html "type std::io::Result")<[()](../primitive.unit.html)>
1.9.0
Moves this TCP stream into or out of nonblocking mode.
This will result in read
, write
, recv
and send
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 Unix platforms, calling this method corresponds to calling fcntl
FIONBIO
. On Windows calling this method corresponds to callingioctlsocket
FIONBIO
.
Reading bytes from a TCP stream in non-blocking mode:
use std::io::{self, Read}; use std:🥅: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 call failed");
let mut buf = vec![]; loop { match stream.read_to_end(&mut buf) { Ok(_) => break, Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
wait_for_fd();
}
Err(e) => panic!("encountered IO error: {}", e),
};
}; println!("bytes: {:?}", buf);Run
impl [Read](../../std/io/trait.Read.html "trait std::io::Read") for [TcpStream](../../std/net/struct.TcpStream.html "struct std:🥅:TcpStream")
[src]
fn [read](../../std/io/trait.Read.html#tymethod.read)(&mut self, buf: [&mut [](../primitive.slice.html)[u8](../primitive.u8.html)[]](../primitive.slice.html)) -> [Result](../../std/io/type.Result.html "type std::io::Result")<[usize](../primitive.usize.html)>
[src]
Pull some bytes from this source into the specified buffer, returning how many bytes were read. Read more
unsafe fn [initializer](../../std/io/trait.Read.html#method.initializer)(&self) -> [Initializer](../../std/io/struct.Initializer.html "struct std::io::Initializer")
[src]
🔬 This is a nightly-only experimental API. (read_initializer
#42788)
Determines if this Read
er can work with buffers of uninitialized memory. Read more
fn [read_to_end](../../std/io/trait.Read.html#method.read%5Fto%5Fend)(&mut self, buf: &mut [Vec](../../std/vec/struct.Vec.html "struct std::vec::Vec")<[u8](../primitive.u8.html)>) -> [Result](../../std/io/type.Result.html "type std::io::Result")<[usize](../primitive.usize.html)>
[src]
Read all bytes until EOF in this source, placing them into buf
. Read more
fn [read_to_string](../../std/io/trait.Read.html#method.read%5Fto%5Fstring)(&mut self, buf: &mut [String](../../std/string/struct.String.html "struct std:🧵:String")) -> [Result](../../std/io/type.Result.html "type std::io::Result")<[usize](../primitive.usize.html)>
[src]
Read all bytes until EOF in this source, appending them to buf
. Read more
fn [read_exact](../../std/io/trait.Read.html#method.read%5Fexact)(&mut self, buf: [&mut [](../primitive.slice.html)[u8](../primitive.u8.html)[]](../primitive.slice.html)) -> [Result](../../std/io/type.Result.html "type std::io::Result")<[()](../primitive.unit.html)>
1.6.0
Read the exact number of bytes required to fill buf
. Read more
`fn by_ref(&mut self) -> &mut Self where
Creates a "by reference" adaptor for this instance of Read
. Read more
ⓘImportant traits for Bytes
fn [bytes](../../std/io/trait.Read.html#method.bytes)(self) -> [Bytes](../../std/io/struct.Bytes.html "struct std::io::Bytes")<Self> where Self: [Sized](../../std/marker/trait.Sized.html "trait std:📑:Sized"),
[src]
Transforms this Read
instance to an [Iterator
] over its bytes. Read more
ⓘImportant traits for Chars
fn [chars](../../std/io/trait.Read.html#method.chars)(self) -> [Chars](../../std/io/struct.Chars.html "struct std::io::Chars")<Self> where Self: [Sized](../../std/marker/trait.Sized.html "trait std:📑:Sized"),
[src]
🔬 This is a nightly-only experimental API. (io
#27802)
the semantics of a partial read/write of where errors happen is currently unclear and may change
Transforms this Read
instance to an [Iterator
] over [char
]s. Read more
ⓘImportant traits for Chain<T, U>
fn [chain](../../std/io/trait.Read.html#method.chain)<R: [Read](../../std/io/trait.Read.html "trait std::io::Read")>(self, next: R) -> [Chain](../../std/io/struct.Chain.html "struct std::io::Chain")<Self, R> where Self: [Sized](../../std/marker/trait.Sized.html "trait std:📑:Sized"),
[src]
Creates an adaptor which will chain this stream with another. Read more
ⓘImportant traits for Take
fn [take](../../std/io/trait.Read.html#method.take)(self, limit: [u64](../primitive.u64.html)) -> [Take](../../std/io/struct.Take.html "struct std::io::Take")<Self> where Self: [Sized](../../std/marker/trait.Sized.html "trait std:📑:Sized"),
[src]
Creates an adaptor which will read at most limit
bytes from it. Read more
impl [Write](../../std/io/trait.Write.html "trait std::io::Write") for [TcpStream](../../std/net/struct.TcpStream.html "struct std:🥅:TcpStream")
[src]
impl<'a> [Read](../../std/io/trait.Read.html "trait std::io::Read") for &'a [TcpStream](../../std/net/struct.TcpStream.html "struct std:🥅:TcpStream")
[src]
fn [read](../../std/io/trait.Read.html#tymethod.read)(&mut self, buf: [&mut [](../primitive.slice.html)[u8](../primitive.u8.html)[]](../primitive.slice.html)) -> [Result](../../std/io/type.Result.html "type std::io::Result")<[usize](../primitive.usize.html)>
[src]
Pull some bytes from this source into the specified buffer, returning how many bytes were read. Read more
unsafe fn [initializer](../../std/io/trait.Read.html#method.initializer)(&self) -> [Initializer](../../std/io/struct.Initializer.html "struct std::io::Initializer")
[src]
🔬 This is a nightly-only experimental API. (read_initializer
#42788)
Determines if this Read
er can work with buffers of uninitialized memory. Read more
fn [read_to_end](../../std/io/trait.Read.html#method.read%5Fto%5Fend)(&mut self, buf: &mut [Vec](../../std/vec/struct.Vec.html "struct std::vec::Vec")<[u8](../primitive.u8.html)>) -> [Result](../../std/io/type.Result.html "type std::io::Result")<[usize](../primitive.usize.html)>
[src]
Read all bytes until EOF in this source, placing them into buf
. Read more
fn [read_to_string](../../std/io/trait.Read.html#method.read%5Fto%5Fstring)(&mut self, buf: &mut [String](../../std/string/struct.String.html "struct std:🧵:String")) -> [Result](../../std/io/type.Result.html "type std::io::Result")<[usize](../primitive.usize.html)>
[src]
Read all bytes until EOF in this source, appending them to buf
. Read more
fn [read_exact](../../std/io/trait.Read.html#method.read%5Fexact)(&mut self, buf: [&mut [](../primitive.slice.html)[u8](../primitive.u8.html)[]](../primitive.slice.html)) -> [Result](../../std/io/type.Result.html "type std::io::Result")<[()](../primitive.unit.html)>
1.6.0
Read the exact number of bytes required to fill buf
. Read more
`fn by_ref(&mut self) -> &mut Self where
Creates a "by reference" adaptor for this instance of Read
. Read more
ⓘImportant traits for Bytes
fn [bytes](../../std/io/trait.Read.html#method.bytes)(self) -> [Bytes](../../std/io/struct.Bytes.html "struct std::io::Bytes")<Self> where Self: [Sized](../../std/marker/trait.Sized.html "trait std:📑:Sized"),
[src]
Transforms this Read
instance to an [Iterator
] over its bytes. Read more
ⓘImportant traits for Chars
fn [chars](../../std/io/trait.Read.html#method.chars)(self) -> [Chars](../../std/io/struct.Chars.html "struct std::io::Chars")<Self> where Self: [Sized](../../std/marker/trait.Sized.html "trait std:📑:Sized"),
[src]
🔬 This is a nightly-only experimental API. (io
#27802)
the semantics of a partial read/write of where errors happen is currently unclear and may change
Transforms this Read
instance to an [Iterator
] over [char
]s. Read more
ⓘImportant traits for Chain<T, U>
fn [chain](../../std/io/trait.Read.html#method.chain)<R: [Read](../../std/io/trait.Read.html "trait std::io::Read")>(self, next: R) -> [Chain](../../std/io/struct.Chain.html "struct std::io::Chain")<Self, R> where Self: [Sized](../../std/marker/trait.Sized.html "trait std:📑:Sized"),
[src]
Creates an adaptor which will chain this stream with another. Read more
ⓘImportant traits for Take
fn [take](../../std/io/trait.Read.html#method.take)(self, limit: [u64](../primitive.u64.html)) -> [Take](../../std/io/struct.Take.html "struct std::io::Take")<Self> where Self: [Sized](../../std/marker/trait.Sized.html "trait std:📑:Sized"),
[src]
Creates an adaptor which will read at most limit
bytes from it. Read more
impl<'a> [Write](../../std/io/trait.Write.html "trait std::io::Write") for &'a [TcpStream](../../std/net/struct.TcpStream.html "struct std:🥅:TcpStream")
[src]
impl [Debug](../../std/fmt/trait.Debug.html "trait std::fmt::Debug") for [TcpStream](../../std/net/struct.TcpStream.html "struct std:🥅:TcpStream")
[src]
impl [AsRawFd](../../std/os/unix/io/trait.AsRawFd.html "trait std::os::unix::io::AsRawFd") for [TcpStream](../../std/net/struct.TcpStream.html "struct std:🥅:TcpStream")
[src]
impl [FromRawFd](../../std/os/unix/io/trait.FromRawFd.html "trait std::os::unix::io::FromRawFd") for [TcpStream](../../std/net/struct.TcpStream.html "struct std:🥅:TcpStream")
1.1.0
impl [IntoRawFd](../../std/os/unix/io/trait.IntoRawFd.html "trait std::os::unix::io::IntoRawFd") for [TcpStream](../../std/net/struct.TcpStream.html "struct std:🥅:TcpStream")
1.4.0
impl [AsRawSocket](../../std/os/windows/io/trait.AsRawSocket.html "trait std::os::windows::io::AsRawSocket") for [TcpStream](../../std/net/struct.TcpStream.html "struct std:🥅:TcpStream")
[src]
impl [FromRawSocket](../../std/os/windows/io/trait.FromRawSocket.html "trait std::os::windows::io::FromRawSocket") for [TcpStream](../../std/net/struct.TcpStream.html "struct std:🥅:TcpStream")
1.1.0
impl [IntoRawSocket](../../std/os/windows/io/trait.IntoRawSocket.html "trait std::os::windows::io::IntoRawSocket") for [TcpStream](../../std/net/struct.TcpStream.html "struct std:🥅:TcpStream")
1.4.0