trellis_net/
listener.rs

1
2// ===== Imports =====
3use std::{io::Error, net::SocketAddr};
4use tokio::net::TcpListener;
5
6use crate::{Address, connection::Connection};
7// ===================
8
9/// # Listener
10/// I/O Object for listening to and accepting `Connection`s.
11pub struct Listener {
12  pub local_addr: Address,
13  listener: TcpListener,
14}
15
16impl Listener {
17  /// ## Constructor
18  /// Creates a new `Listener` instance.
19  pub async fn new(listen_at: Address) -> Result<Self, Error> {
20    let listen_at: SocketAddr = listen_at.into();
21    let listener = TcpListener::bind(listen_at).await?;
22    let local_addr = listener.local_addr()?.into();
23    Ok(Self { local_addr, listener })
24  }
25
26  /// ## Accept
27  /// Accepts an incoming `Connection`.
28  pub async fn accept(&self) -> Result<Connection, Error> {
29    let (stream, _) = self.listener.accept().await?;
30    let conn = Connection::try_from(stream)?;
31    Ok(conn)
32  }
33}