12127
|
1 |
use slab;
|
12126
|
2 |
use mio::tcp::*;
|
|
3 |
use mio::*;
|
|
4 |
use std::io::Write;
|
|
5 |
use std::io;
|
|
6 |
|
|
7 |
use utils;
|
12128
|
8 |
use server::client::HWClient;
|
12126
|
9 |
|
12127
|
10 |
type Slab<T> = slab::Slab<T, Token>;
|
|
11 |
|
12126
|
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<()> {
|
12129
|
33 |
let (sock, addr) = self.listener.accept()?;
|
12126
|
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 |
|
12127
|
40 |
self.clients[token].register(poll, token);
|
12126
|
41 |
|
|
42 |
Ok(())
|
|
43 |
}
|
12127
|
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 |
}
|
12126
|
54 |
}
|
|
55 |
|
12127
|
56 |
|
12126
|
57 |
struct HWRoom {
|
|
58 |
name: String
|
|
59 |
}
|