Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(net): implement more methods for TcpStream #507

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions src/net/tcp/stream.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::io::{IoSlice, IoSliceMut, Read as _, Write as _};
use std::net::SocketAddr;
use std::pin::Pin;
use std::time::Duration;

use crate::future;
use crate::io::{self, Read, Write};
Expand Down Expand Up @@ -96,6 +97,18 @@ impl TcpStream {
}))
}

/// 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.
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doc comment is missing an example. :)

pub async fn connect_timeout(addr: &SocketAddr, timeout: Duration) -> io::Result<TcpStream> {
let stream = io::timeout(timeout, async move { TcpStream::connect(addr).await }).await?;

Ok(stream)
}

/// Returns the local address that this stream is connected to.
///
/// ## Examples
Expand Down Expand Up @@ -255,6 +268,29 @@ impl TcpStream {
self.watcher.get_ref().set_nodelay(nodelay)
}

/// 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
///
/// ```no_run
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::net::TcpStream;
///
/// let stream = TcpStream::connect("127.0.0.1:8080").await
/// .expect("Couldn't connect to the server...");
/// stream.take_error().expect("No error was expected...");
///
/// # Ok(()) }) }
/// ```
pub fn take_error(&self) -> io::Result<Option<io::Error>> {
self.watcher.get_ref().take_error()
}

/// Shuts down the read, write, or both halves of this connection.
///
/// This method will cause all pending and future I/O on the specified portions to return
Expand Down