2 use async_std::net::{SocketAddr, TcpListener, ToSocketAddrs};
3 use async_std::pin::Pin;
4 use async_std::task::{Context, Poll};
5 use futures::{Stream, StreamExt};
10 local_addrs: SocketAddr,
11 listener: TcpListener,
15 pub async fn new<A: ToSocketAddrs + std::fmt::Display>(ip_addrs: A) -> anyhow::Result<Self> {
16 let listener = TcpListener::bind(&ip_addrs).await?;
17 info!("Started TCP server at {}", &ip_addrs);
20 local_addrs: listener.local_addr()?,
25 pub async fn accept(&self) -> anyhow::Result<Connection> {
26 let (stream, ip_addr) = self.listener.accept().await?;
27 debug!("Received connection attempt from {}", ip_addr);
29 Ok(Connection::from(stream))
33 impl Stream for TcpServer {
34 type Item = Connection;
36 fn poll_next(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
37 match futures::executor::block_on(self.listener.incoming().next()) {
38 Some(Ok(tcp_stream)) => {
39 let peer_addr = tcp_stream.peer_addr().expect("Could not retrieve peer IP address");
40 debug!("Received connection attempt from {}", peer_addr);
42 Poll::Ready(Some(Connection::from(tcp_stream)))
46 error!("Encountered error when trying to accept new connection {}", e);
50 None => Poll::Ready(None)