Enum amq_protocol_tcp::TcpStream

source ·
pub enum TcpStream {
    Plain(TcpStream, bool),
    Rustls(Box<StreamOwned<ClientConnection, TcpStream>>),
}
Expand description

Re-export TcpStream Wrapper around plain or TLS TCP streams

Variants§

§

Plain(TcpStream, bool)

Wrapper around std::net::TcpStream

§

Rustls(Box<StreamOwned<ClientConnection, TcpStream>>)

Wrapper around a TLS stream hanled by rustls

Implementations§

source§

impl TcpStream

source

pub fn connect<A>(addr: A) -> Result<TcpStream, Error>
where A: ToSocketAddrs,

Wrapper around std::net::TcpStream::connect

source

pub fn connect_timeout<A>( addr: A, timeout: Duration ) -> Result<TcpStream, Error>
where A: ToSocketAddrs,

Wrapper around std::net::TcpStream::connect_timeout

source

pub fn from_std(stream: TcpStream) -> Result<TcpStream, Error>

Convert from a std::net::TcpStream

source

pub fn is_connected(&self) -> bool

Check whether the stream is connected or not

source

pub fn try_connect(&mut self) -> Result<bool, Error>

Retry the connection. Returns:

  • Ok(true) if connected
  • Ok(false) if connecting
  • Err(_) if an error is encountered
source

pub fn into_tls( self, domain: &str, config: TLSConfig<'_, '_, '_> ) -> Result<TcpStream, HandshakeError>

Enable TLS

source

pub fn into_rustls( self, connector: &RustlsConnector, domain: &str ) -> Result<TcpStream, HandshakeError>

Enable TLS using rustls

source§

impl TcpStream

source

pub fn is_readable(&self) -> Result<(), Error>

Attempt reading from underlying stream, returning Ok(()) if the stream is readable

source

pub fn is_writable(&self) -> Result<(), Error>

Attempt writing to underlying stream, returning Ok(()) if the stream is writable

Methods from Deref<Target = TcpStream>§

1.0.0 · source

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

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)));
1.0.0 · source

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

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)));
1.0.0 · source

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

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");
1.0.0 · source

pub fn try_clone(&self) -> Result<TcpStream, Error>

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...");
1.4.0 · source

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

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

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)
1.4.0 · source

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

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

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)
1.4.0 · source

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

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);
1.4.0 · source

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

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);
1.18.0 · source

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

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 connect to the server...");
let mut buf = [0; 10];
let len = stream.peek(&mut buf).expect("peek failed");
source

pub fn set_linger(&self, linger: Option<Duration>) -> Result<(), Error>

🔬This is a nightly-only experimental API. (tcp_linger)

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");
source

pub fn linger(&self) -> Result<Option<Duration>, Error>

🔬This is a nightly-only experimental API. (tcp_linger)

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)));
1.9.0 · source

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

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");
1.9.0 · source

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

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);
1.9.0 · source

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

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");
1.9.0 · source

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

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);
1.9.0 · source

pub fn take_error(&self) -> Result<Option<Error>, 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
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...");
1.9.0 · source

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

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

Trait Implementations§

source§

impl AsRawFd for &TcpStream

source§

fn as_raw_fd(&self) -> i32

Extracts the raw file descriptor. Read more
source§

impl AsRawFd for TcpStream

source§

fn as_raw_fd(&self) -> i32

Extracts the raw file descriptor. Read more
source§

impl Debug for TcpStream

source§

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

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

impl Deref for TcpStream

§

type Target = TcpStream

The resulting type after dereferencing.
source§

fn deref(&self) -> &<TcpStream as Deref>::Target

Dereferences the value.
source§

impl DerefMut for TcpStream

source§

fn deref_mut(&mut self) -> &mut <TcpStream as Deref>::Target

Mutably dereferences the value.
source§

impl From<StreamOwned<ClientConnection, TcpStream>> for TcpStream

source§

fn from(s: StreamOwned<ClientConnection, TcpStream>) -> TcpStream

Converts to this type from the input type.
source§

impl From<TcpStream> for MidHandshakeTlsStream

source§

fn from(mid: TcpStream) -> MidHandshakeTlsStream

Converts to this type from the input type.
source§

impl FromRawFd for TcpStream

source§

unsafe fn from_raw_fd(fd: i32) -> TcpStream

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

impl Read for TcpStream

source§

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

Pull some bytes from this source into the specified buffer, returning how many bytes were read. Read more
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 read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize, Error>

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

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

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

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

Read the exact number of bytes required to fill buf. 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
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)
Read 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” adaptor 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§

impl TryFrom<TcpStream> for TcpStream

§

type Error = Error

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

fn try_from(s: TcpStream) -> Result<TcpStream, Error>

Performs the conversion.
source§

impl Write for TcpStream

source§

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

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

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

Flush this output stream, ensuring that all intermediately buffered contents reach their destination. Read more
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 write_all(&mut self, buf: &[u8]) -> Result<(), Error>

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

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

Writes a formatted string into this writer, returning any error encountered. 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
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 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<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

source§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

source§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

source§

fn implicit( self, class: Class, constructed: bool, tag: u32 ) -> TaggedParser<'a, Implicit, Self, E>

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> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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> Same for T

§

type Output = T

Should always be Self
source§

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

§

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>,

§

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.
source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

source§

fn vzip(self) -> V

source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

impl<W> Writer for W
where W: Write,

source§

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

Write the given DER-encoded bytes as output.
source§

fn write_byte(&mut self, byte: u8) -> Result<(), Error>

Write a single byte.