You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

81 lines
1.5 KiB

5 years ago
//! Server connection information.
use std::io;
use std::net::SocketAddr;
use mio::event::Source;
5 years ago
use mio::net::TcpListener;
5 years ago
use mio::{Interest, Registry, Token};
5 years ago
use crate::client::Client;
use crate::result::*;
use crate::state::*;
/// Connection information for the server.
#[derive(Debug)]
pub struct Server {
/// listen socket
pub socket: TcpListener,
/// token identifier (0)
pub token: Token,
/// ip address/port
pub addr: SocketAddr,
}
impl Server {
/// Bind to the provided address
pub fn listen<'a>(addr: String, token: Token) -> RudeResult<Server> {
let addr: SocketAddr = try_log!(addr.parse(), "Unable to parse server address: {}", &addr);
let socket: TcpListener = try_log!(
TcpListener::bind(addr),
5 years ago
"Unable to bind to address: {}",
&addr,
);
Ok(Server {
socket,
token,
addr,
})
}
/// Accept a new client connection
pub fn accept(&self, token: Token) -> RudeResult<Client> {
let (socket, addr) = self.socket.accept()?;
Ok(Client {
socket,
token,
addr,
state: State::Login(Login::Username),
})
}
}
impl Source for Server {
5 years ago
fn register(
&mut self,
registry: &Registry,
5 years ago
token: Token,
5 years ago
interest: Interest,
5 years ago
) -> io::Result<()> {
self.socket.register(registry, token, interest)
5 years ago
}
fn reregister(
&mut self,
registry: &Registry,
5 years ago
token: Token,
interest: Interest,
5 years ago
) -> io::Result<()> {
self.socket.reregister(registry, token, interest)
5 years ago
}
fn deregister(&mut self, registry: &Registry) -> io::Result<()> {
self.socket.deregister(registry)
5 years ago
}
}