4 use std::io::Write; |
4 use std::io::Write; |
5 use std::io; |
5 use std::io; |
6 use netbuf; |
6 use netbuf; |
7 |
7 |
8 use utils; |
8 use utils; |
9 use protocol::FrameDecoder; |
9 use protocol::ProtocolDecoder; |
|
10 use protocol::messages; |
|
11 use protocol::messages::HWProtocolMessage::*; |
10 |
12 |
11 pub struct HWClient { |
13 pub struct HWClient { |
12 sock: TcpStream, |
14 sock: TcpStream, |
13 decoder: FrameDecoder, |
15 decoder: ProtocolDecoder, |
14 buf_out: netbuf::Buf |
16 buf_out: netbuf::Buf |
15 } |
17 } |
16 |
18 |
17 impl HWClient { |
19 impl HWClient { |
18 pub fn new(sock: TcpStream) -> HWClient { |
20 pub fn new(sock: TcpStream) -> HWClient { |
19 HWClient { |
21 HWClient { |
20 sock: sock, |
22 sock: sock, |
21 decoder: FrameDecoder::new(), |
23 decoder: ProtocolDecoder::new(), |
22 buf_out: netbuf::Buf::new(), |
24 buf_out: netbuf::Buf::new(), |
23 } |
25 } |
24 } |
26 } |
25 |
27 |
26 pub fn register(&mut self, poll: &Poll, token: Token) { |
28 pub fn register(&mut self, poll: &Poll, token: Token) { |
36 fn send_raw_msg(&mut self, msg: &[u8]) { |
38 fn send_raw_msg(&mut self, msg: &[u8]) { |
37 self.buf_out.write(msg).unwrap(); |
39 self.buf_out.write(msg).unwrap(); |
38 self.flush(); |
40 self.flush(); |
39 } |
41 } |
40 |
42 |
|
43 fn send_msg(&mut self, msg: messages::HWProtocolMessage) { |
|
44 self.send_raw_msg(&msg.to_raw_protocol().into_bytes()); |
|
45 } |
|
46 |
41 fn flush(&mut self) { |
47 fn flush(&mut self) { |
42 self.buf_out.write_to(&mut self.sock).unwrap(); |
48 self.buf_out.write_to(&mut self.sock).unwrap(); |
43 self.sock.flush(); |
49 self.sock.flush(); |
44 } |
50 } |
45 |
51 |
46 pub fn readable(&mut self, poll: &Poll) -> io::Result<()> { |
52 pub fn readable(&mut self, poll: &Poll) -> io::Result<()> { |
47 let v = self.decoder.read_from(&mut self.sock)?; |
53 let v = self.decoder.read_from(&mut self.sock)?; |
48 self.decoder.extract_messages(); |
|
49 println!("Read {} bytes", v); |
54 println!("Read {} bytes", v); |
|
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(); |
50 Ok(()) |
69 Ok(()) |
51 } |
70 } |
52 |
71 |
53 pub fn writable(&mut self, poll: &Poll) -> io::Result<()> { |
72 pub fn writable(&mut self, poll: &Poll) -> io::Result<()> { |
54 self.buf_out.write_to(&mut self.sock)?; |
73 self.buf_out.write_to(&mut self.sock)?; |