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