gameServer2/src/server/server.rs
changeset 12128 f50876f3eff8
parent 12127 36ac9c075d0d
child 12129 07972a8c2433
equal deleted inserted replaced
12127:36ac9c075d0d 12128:f50876f3eff8
       
     1 use slab;
       
     2 use mio::tcp::*;
       
     3 use mio::*;
       
     4 use std::io::Write;
       
     5 use std::io;
       
     6 use netbuf;
       
     7 
       
     8 use utils;
       
     9 use server::client::HWClient;
       
    10 
       
    11 type Slab<T> = slab::Slab<T, Token>;
       
    12 
       
    13 pub struct HWServer {
       
    14     listener: TcpListener,
       
    15     clients: Slab<HWClient>,
       
    16     rooms: Slab<HWRoom>
       
    17 }
       
    18 
       
    19 impl HWServer {
       
    20     pub fn new(listener: TcpListener, clients_limit: usize, rooms_limit: usize) -> HWServer {
       
    21         HWServer {
       
    22             listener: listener,
       
    23             clients: Slab::with_capacity(clients_limit),
       
    24             rooms: Slab::with_capacity(rooms_limit),
       
    25         }
       
    26     }
       
    27 
       
    28     pub fn register(&self, poll: &Poll) -> io::Result<()> {
       
    29         poll.register(&self.listener, utils::SERVER, Ready::readable(),
       
    30                       PollOpt::edge())
       
    31     }
       
    32 
       
    33     pub fn accept(&mut self, poll: &Poll) -> io::Result<()> {
       
    34         let (sock, addr) = self.listener.accept().unwrap();
       
    35         println!("Connected: {}", addr);
       
    36 
       
    37         let client = HWClient::new(sock);
       
    38         let token = self.clients.insert(client)
       
    39             .ok().expect("could not add connection to slab");
       
    40 
       
    41         self.clients[token].register(poll, token);
       
    42 
       
    43         Ok(())
       
    44     }
       
    45 
       
    46     pub fn client_readable(&mut self, poll: &Poll,
       
    47                            token: Token) -> io::Result<()> {
       
    48         self.clients[token].readable(poll)
       
    49     }
       
    50 
       
    51     pub fn client_writable(&mut self, poll: &Poll,
       
    52                            token: Token) -> io::Result<()> {
       
    53         self.clients[token].writable(poll)
       
    54     }
       
    55 }
       
    56 
       
    57 
       
    58 struct HWRoom {
       
    59     name: String
       
    60 }