Skip to content

Commit ef9fe7d

Browse files
feat(net): implement more methods for TcpStream
- connect_timeout - take_error Ref async-rs#499
1 parent 352f18b commit ef9fe7d

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

src/net/tcp/stream.rs

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
use std::io::{IoSlice, IoSliceMut, Read as _, Write as _};
22
use std::net::SocketAddr;
33
use std::pin::Pin;
4+
use std::time::Duration;
45

56
use crate::future;
67
use crate::io::{self, Read, Write};
@@ -96,6 +97,18 @@ impl TcpStream {
9697
}))
9798
}
9899

100+
/// Opens a TCP connection to a remote host with a timeout.
101+
///
102+
/// Unlike `connect`, `connect_timeout` takes a single `SocketAddr` since
103+
/// timeout must be applied to individual addresses.
104+
///
105+
/// It is an error to pass a zero `Duration` to this function.
106+
pub async fn connect_timeout(addr: &SocketAddr, timeout: Duration) -> io::Result<TcpStream> {
107+
let stream = io::timeout(timeout, async move { TcpStream::connect(addr).await }).await?;
108+
109+
Ok(stream)
110+
}
111+
99112
/// Returns the local address that this stream is connected to.
100113
///
101114
/// ## Examples
@@ -255,6 +268,29 @@ impl TcpStream {
255268
self.watcher.get_ref().set_nodelay(nodelay)
256269
}
257270

271+
/// Gets the value of the `SO_ERROR` option on this socket.
272+
///
273+
/// This will retrieve the stored error in the underlying socket, clearing
274+
/// the field in the process. This can be useful for checking errors between
275+
/// calls.
276+
///
277+
/// # Examples
278+
///
279+
/// ```no_run
280+
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
281+
/// #
282+
/// use async_std::net::TcpStream;
283+
///
284+
/// let stream = TcpStream::connect("127.0.0.1:8080").await
285+
/// .expect("Couldn't connect to the server...");
286+
/// stream.take_error().expect("No error was expected...");
287+
///
288+
/// # Ok(()) }) }
289+
/// ```
290+
pub fn take_error(&self) -> io::Result<Option<io::Error>> {
291+
self.watcher.get_ref().take_error()
292+
}
293+
258294
/// Shuts down the read, write, or both halves of this connection.
259295
///
260296
/// This method will cause all pending and future I/O on the specified portions to return

0 commit comments

Comments
 (0)