|
|
|
//! Server connection information.
|
|
|
|
|
|
|
|
use std::io;
|
|
|
|
use std::net::SocketAddr;
|
|
|
|
|
|
|
|
use mio::event::Source;
|
|
|
|
use mio::net::TcpListener;
|
|
|
|
use mio::{Interest, Registry, Token};
|
|
|
|
|
|
|
|
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),
|
|
|
|
"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 {
|
|
|
|
fn register(
|
|
|
|
&mut self,
|
|
|
|
registry: &Registry,
|
|
|
|
token: Token,
|
|
|
|
interest: Interest,
|
|
|
|
) -> io::Result<()> {
|
|
|
|
self.socket.register(registry, token, interest)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn reregister(
|
|
|
|
&mut self,
|
|
|
|
registry: &Registry,
|
|
|
|
token: Token,
|
|
|
|
interest: Interest,
|
|
|
|
) -> io::Result<()> {
|
|
|
|
self.socket.reregister(registry, token, interest)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn deregister(&mut self, registry: &Registry) -> io::Result<()> {
|
|
|
|
self.socket.deregister(registry)
|
|
|
|
}
|
|
|
|
}
|