TcpStream

Struct TcpStream 

Source
pub struct TcpStream { /* private fields */ }
Expand description

A TCP stream between a local and a remote socket.

The socket will be closed when the value is dropped.

The read and write methods can be interrupted using the Canceller object created with the stream.

Otherwise similar to std::net::TcpStream.

Implementations§

Source§

impl TcpStream

Source

pub fn connect<A: ToSocketAddrs>(address: A) -> Result<(Self, Canceller)>

Creates a new TCP stream with an object used to cancel read/write operations, and connects it to a remote address.

Examples found in repository?
examples/example1.rs (line 38)
7fn main() {
8    let (listener, listener_canceller) = TcpListener::bind("127.0.0.1:0").unwrap();
9    let address = listener.local_addr().unwrap();
10    let server = thread::spawn(move || {
11        println!("Server: ready");
12        let (mut socket, socket_canceller, addr) = listener.accept().unwrap();
13        println!("Server: got connection from {}", addr);
14
15        let connection = thread::spawn(move || {
16            println!("Connection: ready");
17            let mut buf = [0; 16];
18            let len = socket.read(&mut buf).unwrap();
19            println!("Connection: read {}", String::from_utf8_lossy(&buf[..len]));
20            println!("Connection: try reading more.");
21            match socket.read(&mut buf) {
22                Ok(0) => println!("Connection: socket closed."),
23                Err(ref e) if is_cancelled(e) => println!("Connection: cancelled."),
24                ref e => panic!("Connection: unexpected {:?}", e),
25            }
26        });
27
28        println!("Server: try accepting more.");
29        if is_cancelled(&listener.accept().unwrap_err()) {
30            println!("Server: accept cancelled.");
31        }
32
33        socket_canceller.cancel().unwrap();
34        connection.join().unwrap();
35    });
36
37    thread::sleep(Duration::from_secs(2));
38    let (mut socket, socket_canceller) = TcpStream::connect(&address).unwrap();
39    let client = thread::spawn(move || {
40        println!("Client: ready");
41        thread::sleep(Duration::from_secs(2));
42        println!("Client: write data.");
43        socket.write(b"Hello!").unwrap();
44        println!("Client: try reading.");
45        let mut buf = [0; 16];
46        match socket.read(&mut buf) {
47            Ok(0) => println!("Client: socket closed."),
48            Err(ref e) if is_cancelled(e) => println!("Client: cancelled."),
49            ref e => panic!("Client: unexpected {:?}", e),
50        }
51    });
52
53    thread::sleep(Duration::from_secs(4));
54    socket_canceller.cancel().unwrap();
55    thread::sleep(Duration::from_secs(2));
56    listener_canceller.cancel().unwrap();
57
58    server.join().unwrap();
59    client.join().unwrap();
60}
Source

pub fn peer_addr(&self) -> Result<SocketAddr>

Returns the socket address of the remote peer of this TCP connection.

Source

pub fn local_addr(&self) -> Result<SocketAddr>

Returns the socket address of the local half of this TCP connection.

Source

pub fn shutdown(&self, how: Shutdown) -> Result<()>

Shuts down the read, write, or both halves of this connection.

Source

pub fn try_clone(&self) -> Result<(Self, Canceller)>

Creates a new independently owned handle to the underlying socket. The Cancellers associated with the original object and its clone are also independent.

Source

pub fn set_read_timeout(&self, duration: Option<Duration>) -> Result<()>

Sets the read timeout.

Source

pub fn set_write_timeout(&self, duration: Option<Duration>) -> Result<()>

Sets the write timeout.

Source

pub fn read_timeout(&self) -> Result<Option<Duration>>

Gets the read timeout.

Source

pub fn write_timeout(&self) -> Result<Option<Duration>>

Gets the write timeout.

Source

pub fn set_nodelay(&self, nodelay: bool) -> Result<()>

Sets the value of the TCP_NODELAY option on this socket.

Source

pub fn nodelay(&self) -> Result<bool>

Gets the value of the TCP_NODELAY option for this socket.

Source

pub fn set_ttl(&self, ttl: u32) -> Result<()>

Sets the value for the IP_TTL option on this socket.

Source

pub fn ttl(&self) -> Result<u32>

Gets the value for the IP_TTL option for this socket.

Source

pub fn take_error(&self) -> Result<Option<Error>>

Gets the value of the SO_ERROR option for this socket.

Source

pub fn set_nonblocking(&self, nonblocking: bool) -> Result<()>

Moves this TCP stream into or out of nonblocking mode.

Trait Implementations§

Source§

impl Debug for TcpStream

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Read for TcpStream

Source§

fn read(&mut self, buf: &mut [u8]) -> Result<usize>

Reads data from the socket. This operation can be cancelled by the associated Canceller object.

1.36.0 · Source§

fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize, Error>

Like read, except that it reads into a slice of buffers. Read more
Source§

fn is_read_vectored(&self) -> bool

🔬This is a nightly-only experimental API. (can_vector)
Determines if this Reader has an efficient read_vectored implementation. Read more
1.0.0 · Source§

fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize, Error>

Reads all bytes until EOF in this source, placing them into buf. Read more
1.0.0 · Source§

fn read_to_string(&mut self, buf: &mut String) -> Result<usize, Error>

Reads all bytes until EOF in this source, appending them to buf. Read more
1.6.0 · Source§

fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), Error>

Reads the exact number of bytes required to fill buf. Read more
Source§

fn read_buf(&mut self, buf: BorrowedCursor<'_>) -> Result<(), Error>

🔬This is a nightly-only experimental API. (read_buf)
Pull some bytes from this source into the specified buffer. Read more
Source§

fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_>) -> Result<(), Error>

🔬This is a nightly-only experimental API. (read_buf)
Reads the exact number of bytes required to fill cursor. Read more
1.0.0 · Source§

fn by_ref(&mut self) -> &mut Self
where Self: Sized,

Creates a “by reference” adapter for this instance of Read. Read more
1.0.0 · Source§

fn bytes(self) -> Bytes<Self>
where Self: Sized,

Transforms this Read instance to an Iterator over its bytes. Read more
1.0.0 · Source§

fn chain<R>(self, next: R) -> Chain<Self, R>
where R: Read, Self: Sized,

Creates an adapter which will chain this stream with another. Read more
1.0.0 · Source§

fn take(self, limit: u64) -> Take<Self>
where Self: Sized,

Creates an adapter which will read at most limit bytes from it. Read more
Source§

fn read_array<const N: usize>(&mut self) -> Result<[u8; N], Error>
where Self: Sized,

🔬This is a nightly-only experimental API. (read_array)
Read and return a fixed array of bytes from this source. Read more
Source§

impl Write for TcpStream

Source§

fn write(&mut self, buf: &[u8]) -> Result<usize>

Writes data to the socket. This operation can be cancelled by the associated Canceller object.

Source§

fn flush(&mut self) -> Result<()>

Flushes this output stream, ensuring that all intermediately buffered contents reach their destination. Read more
1.36.0 · Source§

fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize, Error>

Like write, except that it writes from a slice of buffers. Read more
Source§

fn is_write_vectored(&self) -> bool

🔬This is a nightly-only experimental API. (can_vector)
Determines if this Writer has an efficient write_vectored implementation. Read more
1.0.0 · Source§

fn write_all(&mut self, buf: &[u8]) -> Result<(), Error>

Attempts to write an entire buffer into this writer. Read more
Source§

fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<(), Error>

🔬This is a nightly-only experimental API. (write_all_vectored)
Attempts to write multiple buffers into this writer. Read more
1.0.0 · Source§

fn write_fmt(&mut self, args: Arguments<'_>) -> Result<(), Error>

Writes a formatted string into this writer, returning any error encountered. Read more
1.0.0 · Source§

fn by_ref(&mut self) -> &mut Self
where Self: Sized,

Creates a “by reference” adapter for this instance of Write. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.