]> git.lizzy.rs Git - connect-rs.git/blob - src/tcp/server.rs
fix visibility and props
[connect-rs.git] / src / tcp / server.rs
1 use crate::Connection;
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};
6 use log::*;
7
8 #[allow(dead_code)]
9 pub struct TcpServer {
10     local_addrs: SocketAddr,
11     listener: TcpListener,
12 }
13
14 impl TcpServer {
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);
18
19         Ok(Self {
20             local_addrs: listener.local_addr()?,
21             listener,
22         })
23     }
24
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);
28
29         Ok(Connection::from(stream))
30     }
31 }
32
33 impl Stream for TcpServer {
34     type Item = Connection;
35
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
40                     .peer_addr()
41                     .expect("Could not retrieve peer IP address");
42                 debug!("Received connection attempt from {}", peer_addr);
43
44                 Poll::Ready(Some(Connection::from(tcp_stream)))
45             }
46
47             Some(Err(e)) => {
48                 error!(
49                     "Encountered error when trying to accept new connection {}",
50                     e
51                 );
52                 Poll::Pending
53             }
54
55             None => Poll::Ready(None),
56         }
57     }
58 }