Struct std::net::TcpStream1.0.0[][src]

pub struct TcpStream(_);
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
Run

Implementations

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...");
}
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::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...");
}
Run

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.

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)));
Run

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)));
Run

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
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 call failed");
Run

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
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 failed...");
Run

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 call failed");
Run

An Err is returned if the zero Duration is 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)
Run

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 call failed");
Run

An Err is returned if the zero Duration is 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)
Run

Returns the read timeout of this socket.

If the timeout is None, then read calls 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 call failed");
assert_eq!(stream.read_timeout().unwrap(), None);
Run

Returns the write timeout of this socket.

If the timeout is None, then write calls 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 call failed");
assert_eq!(stream.write_timeout().unwrap(), None);
Run

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
use std::net::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
🔬 This is a nightly-only experimental API. (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
#![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 call failed");
Run
🔬 This is a nightly-only experimental API. (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 call failed");
assert_eq!(stream.linger().unwrap(), Some(Duration::from_secs(0)));
Run

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
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 call failed");
Run

Gets the value of the TCP_NODELAY option 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 call failed");
assert_eq!(stream.nodelay().unwrap_or(false), true);
Run

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
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 call failed");
Run

Gets the value of the IP_TTL option 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 call failed");
assert_eq!(stream.ttl().unwrap_or(0), 100);
Run

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
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...");
Run

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 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 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 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);
Run

Trait Implementations

🔬 This is a nightly-only experimental API. (io_safety #87074)
This is supported on Unix only.

Borrows the file descriptor. Read more

This is supported on Unix only.

Extracts the raw file descriptor. Read more

Extracts the underlying raw socket from this object.

🔬 This is a nightly-only experimental API. (io_safety #87074)

Borrows the socket.

Formats the value using the given formatter. Read more

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

This is supported on Unix only.

Constructs a new instance of Self from the given raw file descriptor. Read more

Creates a new I/O object from the given raw socket. Read more

This is supported on Unix only.

Consumes this object, returning the raw underlying file descriptor. Read more

Consumes this object, returning the raw underlying socket. Read more

Pull some bytes from this source into the specified buffer, returning how many bytes were read. Read more

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

🔬 This is a nightly-only experimental API. (can_vector #69941)

Determines if this Reader has an efficient read_vectored implementation. Read more

Read all bytes until EOF in this source, placing them into buf. Read more

Read all bytes until EOF in this source, appending them to buf. Read more

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

🔬 This is a nightly-only experimental API. (read_buf #78485)

Pull some bytes from this source into the specified buffer. Read more

🔬 This is a nightly-only experimental API. (read_buf #78485)

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

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

Transforms this Read instance to an Iterator over its bytes. Read more

Creates an adapter which will chain this stream with another. Read more

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

Pull some bytes from this source into the specified buffer, returning how many bytes were read. Read more

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

🔬 This is a nightly-only experimental API. (can_vector #69941)

Determines if this Reader has an efficient read_vectored implementation. Read more

Read all bytes until EOF in this source, placing them into buf. Read more

Read all bytes until EOF in this source, appending them to buf. Read more

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

🔬 This is a nightly-only experimental API. (read_buf #78485)

Pull some bytes from this source into the specified buffer. Read more

🔬 This is a nightly-only experimental API. (read_buf #78485)

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

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

Transforms this Read instance to an Iterator over its bytes. Read more

Creates an adapter which will chain this stream with another. Read more

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

Write a buffer into this writer, returning how many bytes were written. Read more

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

🔬 This is a nightly-only experimental API. (can_vector #69941)

Determines if this Writer has an efficient write_vectored implementation. Read more

Flush this output stream, ensuring that all intermediately buffered contents reach their destination. Read more

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

🔬 This is a nightly-only experimental API. (write_all_vectored #70436)

Attempts to write multiple buffers into this writer. Read more

Writes a formatted string into this writer, returning any error encountered. Read more

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

Write a buffer into this writer, returning how many bytes were written. Read more

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

🔬 This is a nightly-only experimental API. (can_vector #69941)

Determines if this Writer has an efficient write_vectored implementation. Read more

Flush this output stream, ensuring that all intermediately buffered contents reach their destination. Read more

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

🔬 This is a nightly-only experimental API. (write_all_vectored #70436)

Attempts to write multiple buffers into this writer. Read more

Writes a formatted string into this writer, returning any error encountered. Read more

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

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Performs the conversion.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.