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