Struct tokio::net::tcp::ReadHalf

source ·
pub struct ReadHalf<'a>(/* private fields */);
Expand description

Borrowed read half of a TcpStream, created by split.

Reading from a ReadHalf is usually done using the convenience methods found on the AsyncReadExt trait.

Implementations§

source§

impl ReadHalf<'_>

source

pub fn poll_peek( &mut self, cx: &mut Context<'_>, buf: &mut ReadBuf<'_> ) -> Poll<Result<usize>>

Attempts to receive data on the socket, without removing that data from the queue, registering the current task for wakeup if data is not yet available.

Note that on multiple calls to poll_peek or poll_read, only the Waker from the Context passed to the most recent call is scheduled to receive a wakeup.

See the TcpStream::poll_peek level documentation for more details.

Examples
use tokio::io::{self, ReadBuf};
use tokio::net::TcpStream;

use futures::future::poll_fn;

#[tokio::main]
async fn main() -> io::Result<()> {
    let mut stream = TcpStream::connect("127.0.0.1:8000").await?;
    let (mut read_half, _) = stream.split();
    let mut buf = [0; 10];
    let mut buf = ReadBuf::new(&mut buf);

    poll_fn(|cx| {
        read_half.poll_peek(cx, &mut buf)
    }).await?;

    Ok(())
}
source

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

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.

See the TcpStream::peek level documentation for more details.

Examples
use tokio::net::TcpStream;
use tokio::io::AsyncReadExt;
use std::error::Error;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    // Connect to a peer
    let mut stream = TcpStream::connect("127.0.0.1:8080").await?;
    let (mut read_half, _) = stream.split();

    let mut b1 = [0; 10];
    let mut b2 = [0; 10];

    // Peek at the data
    let n = read_half.peek(&mut b1).await?;

    // Read the data
    assert_eq!(n, read_half.read(&mut b2[..n]).await?);
    assert_eq!(&b1[..n], &b2[..n]);

    Ok(())
}

The read method is defined on the AsyncReadExt trait.

source

pub async fn ready(&self, interest: Interest) -> Result<Ready>

Waits for any of the requested ready states.

This function is usually paired with try_read(). It can be used instead of readable() to check the returned ready set for Ready::READABLE and Ready::READ_CLOSED events.

The function may complete without the socket being ready. This is a false-positive and attempting an operation will return with io::ErrorKind::WouldBlock. The function can also return with an empty Ready set, so you should always check the returned value and possibly wait again if the requested states are not set.

This function is equivalent to TcpStream::ready.

Cancel safety

This method is cancel safe. Once a readiness event occurs, the method will continue to return immediately until the readiness event is consumed by an attempt to read or write that fails with WouldBlock or Poll::Pending.

source

pub async fn readable(&self) -> Result<()>

Waits for the socket to become readable.

This function is equivalent to ready(Interest::READABLE) and is usually paired with try_read().

This function is also equivalent to TcpStream::ready.

Cancel safety

This method is cancel safe. Once a readiness event occurs, the method will continue to return immediately until the readiness event is consumed by an attempt to read that fails with WouldBlock or Poll::Pending.

source

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

Tries to read data from the stream into the provided buffer, returning how many bytes were read.

Receives any pending data from the socket but does not wait for new data to arrive. On success, returns the number of bytes read. Because try_read() is non-blocking, the buffer does not have to be stored by the async task and can exist entirely on the stack.

Usually, readable() or ready() is used with this function.

Return

If data is successfully read, Ok(n) is returned, where n is the number of bytes read. If n is 0, then it can indicate one of two scenarios:

  1. The stream’s read half is closed and will no longer yield data.
  2. The specified buffer was 0 bytes in length.

If the stream is not ready to read data, Err(io::ErrorKind::WouldBlock) is returned.

source

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

Tries to read data from the stream into the provided buffers, returning how many bytes were read.

Data is copied to fill each buffer in order, with the final buffer written to possibly being only partially filled. This method behaves equivalently to a single call to try_read() with concatenated buffers.

Receives any pending data from the socket but does not wait for new data to arrive. On success, returns the number of bytes read. Because try_read_vectored() is non-blocking, the buffer does not have to be stored by the async task and can exist entirely on the stack.

Usually, readable() or ready() is used with this function.

Return

If data is successfully read, Ok(n) is returned, where n is the number of bytes read. Ok(0) indicates the stream’s read half is closed and will no longer yield data. If the stream is not ready to read data Err(io::ErrorKind::WouldBlock) is returned.

source

pub fn try_read_buf<B: BufMut>(&self, buf: &mut B) -> Result<usize>

Tries to read data from the stream into the provided buffer, advancing the buffer’s internal cursor, returning how many bytes were read.

Receives any pending data from the socket but does not wait for new data to arrive. On success, returns the number of bytes read. Because try_read_buf() is non-blocking, the buffer does not have to be stored by the async task and can exist entirely on the stack.

Usually, readable() or ready() is used with this function.

Return

If data is successfully read, Ok(n) is returned, where n is the number of bytes read. Ok(0) indicates the stream’s read half is closed and will no longer yield data. If the stream is not ready to read data Err(io::ErrorKind::WouldBlock) is returned.

source

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

Returns the remote address that this stream is connected to.

source

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

Returns the local address that this stream is bound to.

Trait Implementations§

source§

impl AsRef<TcpStream> for ReadHalf<'_>

source§

fn as_ref(&self) -> &TcpStream

Converts this type into a shared reference of the (usually inferred) input type.
source§

impl AsyncRead for ReadHalf<'_>

source§

fn poll_read( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_> ) -> Poll<Result<()>>

Attempts to read from the AsyncRead into buf. Read more
source§

impl<'a> Debug for ReadHalf<'a>

source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<'a> RefUnwindSafe for ReadHalf<'a>

§

impl<'a> Send for ReadHalf<'a>

§

impl<'a> Sync for ReadHalf<'a>

§

impl<'a> Unpin for ReadHalf<'a>

§

impl<'a> UnwindSafe for ReadHalf<'a>

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<R> AsyncReadExt for R
where R: AsyncRead + ?Sized,

source§

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

Creates a new AsyncRead instance that chains this stream with next. Read more
source§

fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> Read<'a, Self>
where Self: Unpin,

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

fn read_buf<'a, B>(&'a mut self, buf: &'a mut B) -> ReadBuf<'a, Self, B>
where Self: Sized + Unpin, B: BufMut,

Pulls some bytes from this source into the specified buffer, advancing the buffer’s internal cursor. Read more
source§

fn read_exact<'a>(&'a mut self, buf: &'a mut [u8]) -> ReadExact<'a, Self>
where Self: Unpin,

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

fn read_u8(&mut self) -> ReadU8<&mut Self>
where Self: Unpin,

Reads an unsigned 8 bit integer from the underlying reader. Read more
source§

fn read_i8(&mut self) -> ReadI8<&mut Self>
where Self: Unpin,

Reads a signed 8 bit integer from the underlying reader. Read more
source§

fn read_u16(&mut self) -> ReadU16<&mut Self>
where Self: Unpin,

Reads an unsigned 16-bit integer in big-endian order from the underlying reader. Read more
source§

fn read_i16(&mut self) -> ReadI16<&mut Self>
where Self: Unpin,

Reads a signed 16-bit integer in big-endian order from the underlying reader. Read more
source§

fn read_u32(&mut self) -> ReadU32<&mut Self>
where Self: Unpin,

Reads an unsigned 32-bit integer in big-endian order from the underlying reader. Read more
source§

fn read_i32(&mut self) -> ReadI32<&mut Self>
where Self: Unpin,

Reads a signed 32-bit integer in big-endian order from the underlying reader. Read more
source§

fn read_u64(&mut self) -> ReadU64<&mut Self>
where Self: Unpin,

Reads an unsigned 64-bit integer in big-endian order from the underlying reader. Read more
source§

fn read_i64(&mut self) -> ReadI64<&mut Self>
where Self: Unpin,

Reads an signed 64-bit integer in big-endian order from the underlying reader. Read more
source§

fn read_u128(&mut self) -> ReadU128<&mut Self>
where Self: Unpin,

Reads an unsigned 128-bit integer in big-endian order from the underlying reader. Read more
source§

fn read_i128(&mut self) -> ReadI128<&mut Self>
where Self: Unpin,

Reads an signed 128-bit integer in big-endian order from the underlying reader. Read more
source§

fn read_f32(&mut self) -> ReadF32<&mut Self>
where Self: Unpin,

Reads an 32-bit floating point type in big-endian order from the underlying reader. Read more
source§

fn read_f64(&mut self) -> ReadF64<&mut Self>
where Self: Unpin,

Reads an 64-bit floating point type in big-endian order from the underlying reader. Read more
source§

fn read_u16_le(&mut self) -> ReadU16Le<&mut Self>
where Self: Unpin,

Reads an unsigned 16-bit integer in little-endian order from the underlying reader. Read more
source§

fn read_i16_le(&mut self) -> ReadI16Le<&mut Self>
where Self: Unpin,

Reads a signed 16-bit integer in little-endian order from the underlying reader. Read more
source§

fn read_u32_le(&mut self) -> ReadU32Le<&mut Self>
where Self: Unpin,

Reads an unsigned 32-bit integer in little-endian order from the underlying reader. Read more
source§

fn read_i32_le(&mut self) -> ReadI32Le<&mut Self>
where Self: Unpin,

Reads a signed 32-bit integer in little-endian order from the underlying reader. Read more
source§

fn read_u64_le(&mut self) -> ReadU64Le<&mut Self>
where Self: Unpin,

Reads an unsigned 64-bit integer in little-endian order from the underlying reader. Read more
source§

fn read_i64_le(&mut self) -> ReadI64Le<&mut Self>
where Self: Unpin,

Reads an signed 64-bit integer in little-endian order from the underlying reader. Read more
source§

fn read_u128_le(&mut self) -> ReadU128Le<&mut Self>
where Self: Unpin,

Reads an unsigned 128-bit integer in little-endian order from the underlying reader. Read more
source§

fn read_i128_le(&mut self) -> ReadI128Le<&mut Self>
where Self: Unpin,

Reads an signed 128-bit integer in little-endian order from the underlying reader. Read more
source§

fn read_f32_le(&mut self) -> ReadF32Le<&mut Self>
where Self: Unpin,

Reads an 32-bit floating point type in little-endian order from the underlying reader. Read more
source§

fn read_f64_le(&mut self) -> ReadF64Le<&mut Self>
where Self: Unpin,

Reads an 64-bit floating point type in little-endian order from the underlying reader. Read more
source§

fn read_to_end<'a>(&'a mut self, buf: &'a mut Vec<u8>) -> ReadToEnd<'a, Self>
where Self: Unpin,

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

fn read_to_string<'a>( &'a mut self, dst: &'a mut String ) -> ReadToString<'a, Self>
where Self: Unpin,

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

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

Creates an adaptor which reads at most limit bytes from it. 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>,

§

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.