12128
|
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;
|
12136
|
9 |
use protocol::ProtocolDecoder;
|
|
10 |
use protocol::messages;
|
|
11 |
use protocol::messages::HWProtocolMessage::*;
|
12128
|
12 |
|
|
13 |
pub struct HWClient {
|
|
14 |
sock: TcpStream,
|
12136
|
15 |
decoder: ProtocolDecoder,
|
12128
|
16 |
buf_out: netbuf::Buf
|
|
17 |
}
|
|
18 |
|
|
19 |
impl HWClient {
|
|
20 |
pub fn new(sock: TcpStream) -> HWClient {
|
|
21 |
HWClient {
|
|
22 |
sock: sock,
|
12136
|
23 |
decoder: ProtocolDecoder::new(),
|
12128
|
24 |
buf_out: netbuf::Buf::new(),
|
|
25 |
}
|
|
26 |
}
|
|
27 |
|
|
28 |
pub fn register(&mut self, poll: &Poll, token: Token) {
|
|
29 |
poll.register(&self.sock, token, Ready::readable(),
|
|
30 |
PollOpt::edge())
|
|
31 |
.ok().expect("could not register socket with event loop");
|
|
32 |
|
|
33 |
self.send_raw_msg(
|
|
34 |
format!("CONNECTED\nHedgewars server http://www.hedgewars.org/\n{}\n\n"
|
|
35 |
, utils::PROTOCOL_VERSION).as_bytes());
|
|
36 |
}
|
|
37 |
|
|
38 |
fn send_raw_msg(&mut self, msg: &[u8]) {
|
|
39 |
self.buf_out.write(msg).unwrap();
|
|
40 |
self.flush();
|
|
41 |
}
|
|
42 |
|
12136
|
43 |
fn send_msg(&mut self, msg: messages::HWProtocolMessage) {
|
|
44 |
self.send_raw_msg(&msg.to_raw_protocol().into_bytes());
|
|
45 |
}
|
|
46 |
|
12128
|
47 |
fn flush(&mut self) {
|
|
48 |
self.buf_out.write_to(&mut self.sock).unwrap();
|
|
49 |
self.sock.flush();
|
|
50 |
}
|
|
51 |
|
|
52 |
pub fn readable(&mut self, poll: &Poll) -> io::Result<()> {
|
12129
|
53 |
let v = self.decoder.read_from(&mut self.sock)?;
|
|
54 |
println!("Read {} bytes", v);
|
12136
|
55 |
let mut response = Vec::new();
|
|
56 |
{
|
|
57 |
let msgs = self.decoder.extract_messages();
|
|
58 |
for msg in msgs {
|
|
59 |
match msg {
|
|
60 |
Ping => response.push(Pong),
|
|
61 |
_ => println!("Unknown message")
|
|
62 |
}
|
|
63 |
}
|
|
64 |
}
|
|
65 |
for r in response {
|
|
66 |
self.send_msg(r);
|
|
67 |
}
|
|
68 |
self.decoder.sweep();
|
12128
|
69 |
Ok(())
|
|
70 |
}
|
|
71 |
|
|
72 |
pub fn writable(&mut self, poll: &Poll) -> io::Result<()> {
|
|
73 |
self.buf_out.write_to(&mut self.sock)?;
|
|
74 |
Ok(())
|
|
75 |
}
|
|
76 |
}
|