|
1 use slab::*; |
|
2 use mio::tcp::*; |
|
3 use mio::*; |
|
4 use mio; |
|
5 use std::io::Write; |
|
6 use std::io; |
|
7 |
|
8 use utils; |
|
9 |
|
10 pub struct HWServer { |
|
11 listener: TcpListener, |
|
12 clients: Slab<HWClient>, |
|
13 rooms: Slab<HWRoom> |
|
14 } |
|
15 |
|
16 impl HWServer { |
|
17 pub fn new(listener: TcpListener, clients_limit: usize, rooms_limit: usize) -> HWServer { |
|
18 HWServer { |
|
19 listener: listener, |
|
20 clients: Slab::with_capacity(clients_limit), |
|
21 rooms: Slab::with_capacity(rooms_limit), |
|
22 } |
|
23 } |
|
24 |
|
25 pub fn register(&self, poll: &Poll) -> io::Result<()> { |
|
26 poll.register(&self.listener, utils::SERVER, Ready::readable(), |
|
27 PollOpt::edge()) |
|
28 } |
|
29 |
|
30 pub fn accept(&mut self, poll: &Poll) -> io::Result<()> { |
|
31 let (sock, addr) = self.listener.accept().unwrap(); |
|
32 println!("Connected: {}", addr); |
|
33 |
|
34 let client = HWClient::new(sock); |
|
35 let token = self.clients.insert(client) |
|
36 .ok().expect("could not add connection to slab"); |
|
37 |
|
38 self.clients[token].send_raw_msg( |
|
39 format!("CONNECTED\nHedgewars server http://www.hedgewars.org/\n{}\n\n" |
|
40 , utils::PROTOCOL_VERSION).as_bytes()); |
|
41 |
|
42 self.clients[token].uid = Some(token); |
|
43 poll.register(&self.clients[token].sock, mio::Token(token), Ready::readable(), |
|
44 PollOpt::edge() | PollOpt::oneshot()) |
|
45 .ok().expect("could not register socket with event loop"); |
|
46 |
|
47 Ok(()) |
|
48 } |
|
49 } |
|
50 |
|
51 struct HWClient { |
|
52 sock: TcpStream, |
|
53 uid: Option<usize> |
|
54 } |
|
55 |
|
56 impl HWClient { |
|
57 fn new(sock: TcpStream) -> HWClient { |
|
58 HWClient { |
|
59 sock: sock, |
|
60 uid: None |
|
61 } |
|
62 } |
|
63 |
|
64 fn send_raw_msg(&mut self, msg: &[u8]) { |
|
65 self.sock.write_all(msg).unwrap(); |
|
66 } |
|
67 } |
|
68 |
|
69 struct HWRoom { |
|
70 name: String |
|
71 } |