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;
|
12129
|
9 |
use protocol::FrameDecoder;
|
12128
|
10 |
|
|
11 |
pub struct HWClient {
|
|
12 |
sock: TcpStream,
|
12129
|
13 |
decoder: FrameDecoder,
|
12128
|
14 |
buf_out: netbuf::Buf
|
|
15 |
}
|
|
16 |
|
|
17 |
impl HWClient {
|
|
18 |
pub fn new(sock: TcpStream) -> HWClient {
|
|
19 |
HWClient {
|
|
20 |
sock: sock,
|
12129
|
21 |
decoder: FrameDecoder::new(),
|
12128
|
22 |
buf_out: netbuf::Buf::new(),
|
|
23 |
}
|
|
24 |
}
|
|
25 |
|
|
26 |
pub fn register(&mut self, poll: &Poll, token: Token) {
|
|
27 |
poll.register(&self.sock, token, Ready::readable(),
|
|
28 |
PollOpt::edge())
|
|
29 |
.ok().expect("could not register socket with event loop");
|
|
30 |
|
|
31 |
self.send_raw_msg(
|
|
32 |
format!("CONNECTED\nHedgewars server http://www.hedgewars.org/\n{}\n\n"
|
|
33 |
, utils::PROTOCOL_VERSION).as_bytes());
|
|
34 |
}
|
|
35 |
|
|
36 |
fn send_raw_msg(&mut self, msg: &[u8]) {
|
|
37 |
self.buf_out.write(msg).unwrap();
|
|
38 |
self.flush();
|
|
39 |
}
|
|
40 |
|
|
41 |
fn flush(&mut self) {
|
|
42 |
self.buf_out.write_to(&mut self.sock).unwrap();
|
|
43 |
self.sock.flush();
|
|
44 |
}
|
|
45 |
|
|
46 |
pub fn readable(&mut self, poll: &Poll) -> io::Result<()> {
|
12129
|
47 |
let v = self.decoder.read_from(&mut self.sock)?;
|
|
48 |
self.decoder.extract_messages();
|
|
49 |
println!("Read {} bytes", v);
|
12128
|
50 |
Ok(())
|
|
51 |
}
|
|
52 |
|
|
53 |
pub fn writable(&mut self, poll: &Poll) -> io::Result<()> {
|
|
54 |
self.buf_out.write_to(&mut self.sock)?;
|
|
55 |
Ok(())
|
|
56 |
}
|
|
57 |
}
|