#![cfg(feature = "tokio")]
use std::{io::Result, net::SocketAddr, sync::Arc};
use tokio::net::TcpListener;
pub mod auth;
pub mod connection;
pub use crate::{
server::auth::Auth,
server::connection::{
associate::{Associate, AssociatedUdpSocket},
bind::Bind,
connect::Connect,
Connection, IncomingConnection,
},
};
pub struct Server {
listener: TcpListener,
auth: Arc<dyn Auth + Send + Sync>,
}
impl Server {
#[inline]
pub fn new(listener: TcpListener, auth: Arc<dyn Auth + Send + Sync>) -> Self {
Self { listener, auth }
}
#[inline]
pub async fn bind(addr: SocketAddr, auth: Arc<dyn Auth + Send + Sync>) -> Result<Self> {
let socket = if addr.is_ipv4() {
tokio::net::TcpSocket::new_v4()?
} else {
tokio::net::TcpSocket::new_v6()?
};
socket.set_reuseaddr(true)?;
socket.bind(addr)?;
let listener = socket.listen(1024)?;
Ok(Self::new(listener, auth))
}
#[inline]
pub async fn accept(&self) -> Result<(IncomingConnection, SocketAddr)> {
let (stream, addr) = self.listener.accept().await?;
Ok((IncomingConnection::new(stream, self.auth.clone()), addr))
}
#[inline]
pub fn local_addr(&self) -> Result<SocketAddr> {
self.listener.local_addr()
}
}