tcp: add ascyc fn TcpListener::accept (#1242)

Refs: #1209
This commit is contained in:
Carl Lerche 2019-07-03 09:49:56 -07:00 committed by GitHub
parent c531865d2c
commit 3e898f58a5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 46 additions and 0 deletions

View File

@ -25,6 +25,7 @@ publish = false
incoming = ["futures-core-preview"]
[dependencies]
async-util = { git = "https://github.com/tokio-rs/async" }
tokio-io = { version = "0.2.0", path = "../tokio-io" }
tokio-reactor = { version = "0.2.0", path = "../tokio-reactor" }
bytes = "0.4"
@ -38,3 +39,4 @@ futures-core-preview = { version = "0.3.0-alpha.16", optional = true }
#env_logger = { version = "0.5", default-features = false }
#net2 = "*"
tokio = { version = "0.2.0", path = "../tokio" }
tokio-test = { version = "0.2.0", path = "../tokio-test" }

View File

@ -2,6 +2,7 @@
#![deny(missing_docs, missing_debug_implementations, rust_2018_idioms)]
#![cfg_attr(test, deny(warnings))]
#![doc(test(no_crate_inject, attr(deny(rust_2018_idioms))))]
#![feature(async_await)]
//! TCP bindings for `tokio`.
//!

View File

@ -110,6 +110,24 @@ impl TcpListener {
Poll::Ready(Ok((io, addr)))
}
/// Accept a new incoming connection from this listener.
///
/// This function will yield once a new TCP connection is established. When
/// established, the corresponding [`TcpStream`] and the remote peer's
/// address will be returned.
///
/// [`TcpStream`]: ../struct.TcpStream.html
///
/// # Examples
///
/// ```
/// unimplemented!();
/// ```
pub async fn accept(&mut self) -> io::Result<(TcpStream, SocketAddr)> {
use async_util::future::poll_fn;
poll_fn(|cx| self.poll_accept(cx)).await
}
/// Attempt to accept a connection and create a new connected `TcpStream` if
/// successful.
///

View File

@ -0,0 +1,25 @@
#![deny(warnings, rust_2018_idioms)]
#![feature(async_await)]
use tokio::net::{TcpListener, TcpStream};
use tokio::sync::oneshot;
use tokio_test::assert_ok;
#[tokio::test]
async fn accept() {
let addr = "127.0.0.1:0".parse().unwrap();
let mut listener = assert_ok!(TcpListener::bind(&addr));
let addr = listener.local_addr().unwrap();
let (tx, rx) = oneshot::channel();
tokio::spawn(async move {
let (socket, _) = assert_ok!(listener.accept().await);
assert_ok!(tx.send(socket));
});
let cli = assert_ok!(TcpStream::connect(&addr).await);
let srv = assert_ok!(rx.await);
assert_eq!(cli.local_addr().unwrap(), srv.peer_addr().unwrap());
}