13119
|
1 |
extern crate slab;
|
|
2 |
|
13414
|
3 |
use std::{
|
|
4 |
io, io::{Error, ErrorKind, Write},
|
|
5 |
net::{SocketAddr, IpAddr, Ipv4Addr},
|
|
6 |
collections::VecDeque
|
|
7 |
};
|
|
8 |
|
|
9 |
use mio::{
|
|
10 |
net::{TcpStream, TcpListener},
|
|
11 |
Poll, PollOpt, Ready, Token
|
|
12 |
};
|
|
13 |
use netbuf;
|
13119
|
14 |
use slab::Slab;
|
|
15 |
|
13414
|
16 |
use utils;
|
|
17 |
use protocol::{ProtocolDecoder, messages::*};
|
|
18 |
use super::{
|
|
19 |
server::{HWServer, PendingMessage, Destination},
|
|
20 |
client::ClientId
|
|
21 |
};
|
|
22 |
|
|
23 |
const MAX_BYTES_PER_READ: usize = 2048;
|
13119
|
24 |
|
13414
|
25 |
#[derive(PartialEq, Copy, Clone)]
|
|
26 |
pub enum NetworkClientState {
|
|
27 |
Idle,
|
|
28 |
NeedsWrite,
|
|
29 |
NeedsRead,
|
|
30 |
Closed,
|
|
31 |
}
|
|
32 |
|
|
33 |
type NetworkResult<T> = io::Result<(T, NetworkClientState)>;
|
13119
|
34 |
|
|
35 |
pub struct NetworkClient {
|
|
36 |
id: ClientId,
|
|
37 |
socket: TcpStream,
|
|
38 |
peer_addr: SocketAddr,
|
|
39 |
decoder: ProtocolDecoder,
|
13414
|
40 |
buf_out: netbuf::Buf
|
13119
|
41 |
}
|
|
42 |
|
|
43 |
impl NetworkClient {
|
|
44 |
pub fn new(id: ClientId, socket: TcpStream, peer_addr: SocketAddr) -> NetworkClient {
|
|
45 |
NetworkClient {
|
|
46 |
id, socket, peer_addr,
|
|
47 |
decoder: ProtocolDecoder::new(),
|
13414
|
48 |
buf_out: netbuf::Buf::new()
|
13119
|
49 |
}
|
|
50 |
}
|
|
51 |
|
13414
|
52 |
pub fn read_messages(&mut self) -> NetworkResult<Vec<HWProtocolMessage>> {
|
|
53 |
let mut bytes_read = 0;
|
|
54 |
let result = loop {
|
|
55 |
match self.decoder.read_from(&mut self.socket) {
|
|
56 |
Ok(bytes) => {
|
|
57 |
debug!("Read {} bytes", bytes);
|
|
58 |
bytes_read += bytes;
|
|
59 |
if bytes == 0 {
|
|
60 |
let result = if bytes_read == 0 {
|
|
61 |
info!("EOF for client {} ({})", self.id, self.peer_addr);
|
|
62 |
(Vec::new(), NetworkClientState::Closed)
|
|
63 |
} else {
|
|
64 |
(self.decoder.extract_messages(), NetworkClientState::NeedsRead)
|
|
65 |
};
|
|
66 |
break Ok(result);
|
|
67 |
}
|
|
68 |
else if bytes_read >= MAX_BYTES_PER_READ {
|
|
69 |
break Ok((self.decoder.extract_messages(), NetworkClientState::NeedsRead))
|
|
70 |
}
|
|
71 |
}
|
|
72 |
Err(ref error) if error.kind() == ErrorKind::WouldBlock => {
|
|
73 |
let messages = if bytes_read == 0 {
|
|
74 |
Vec::new()
|
|
75 |
} else {
|
|
76 |
self.decoder.extract_messages()
|
|
77 |
};
|
|
78 |
break Ok((messages, NetworkClientState::Idle));
|
|
79 |
}
|
|
80 |
Err(error) =>
|
|
81 |
break Err(error)
|
|
82 |
}
|
|
83 |
};
|
|
84 |
self.decoder.sweep();
|
|
85 |
result
|
|
86 |
}
|
|
87 |
|
|
88 |
pub fn flush(&mut self) -> NetworkResult<()> {
|
|
89 |
let result = loop {
|
|
90 |
match self.buf_out.write_to(&mut self.socket) {
|
|
91 |
Ok(bytes) if self.buf_out.is_empty() || bytes == 0 =>
|
|
92 |
break Ok(((), NetworkClientState::Idle)),
|
|
93 |
Ok(bytes) =>
|
|
94 |
(),
|
|
95 |
Err(ref error) if error.kind() == ErrorKind::Interrupted
|
|
96 |
|| error.kind() == ErrorKind::WouldBlock => {
|
|
97 |
break Ok(((), NetworkClientState::NeedsWrite));
|
|
98 |
},
|
|
99 |
Err(error) =>
|
|
100 |
break Err(error)
|
|
101 |
}
|
|
102 |
};
|
|
103 |
self.socket.flush()?;
|
|
104 |
result
|
|
105 |
}
|
|
106 |
|
13119
|
107 |
pub fn send_raw_msg(&mut self, msg: &[u8]) {
|
|
108 |
self.buf_out.write(msg).unwrap();
|
|
109 |
}
|
|
110 |
|
|
111 |
pub fn send_string(&mut self, msg: &String) {
|
|
112 |
self.send_raw_msg(&msg.as_bytes());
|
|
113 |
}
|
|
114 |
|
|
115 |
pub fn send_msg(&mut self, msg: HWServerMessage) {
|
|
116 |
self.send_string(&msg.to_raw_protocol());
|
|
117 |
}
|
|
118 |
}
|
|
119 |
|
|
120 |
pub struct NetworkLayer {
|
|
121 |
listener: TcpListener,
|
|
122 |
server: HWServer,
|
|
123 |
|
13414
|
124 |
clients: Slab<NetworkClient>,
|
|
125 |
pending: VecDeque<(ClientId, NetworkClientState)>
|
13119
|
126 |
}
|
|
127 |
|
|
128 |
impl NetworkLayer {
|
|
129 |
pub fn new(listener: TcpListener, clients_limit: usize, rooms_limit: usize) -> NetworkLayer {
|
|
130 |
let server = HWServer::new(clients_limit, rooms_limit);
|
|
131 |
let clients = Slab::with_capacity(clients_limit);
|
13414
|
132 |
let pending = VecDeque::with_capacity(clients_limit);
|
|
133 |
NetworkLayer {listener, server, clients, pending}
|
13119
|
134 |
}
|
|
135 |
|
|
136 |
pub fn register_server(&self, poll: &Poll) -> io::Result<()> {
|
|
137 |
poll.register(&self.listener, utils::SERVER, Ready::readable(),
|
|
138 |
PollOpt::edge())
|
|
139 |
}
|
|
140 |
|
|
141 |
fn deregister_client(&mut self, poll: &Poll, id: ClientId) {
|
|
142 |
let mut client_exists = false;
|
13414
|
143 |
if let Some(ref client) = self.clients.get(id) {
|
13119
|
144 |
poll.deregister(&client.socket)
|
|
145 |
.ok().expect("could not deregister socket");
|
|
146 |
info!("client {} ({}) removed", client.id, client.peer_addr);
|
|
147 |
client_exists = true;
|
|
148 |
}
|
|
149 |
if client_exists {
|
|
150 |
self.clients.remove(id);
|
|
151 |
}
|
|
152 |
}
|
|
153 |
|
|
154 |
fn register_client(&mut self, poll: &Poll, id: ClientId, client_socket: TcpStream, addr: SocketAddr) {
|
|
155 |
poll.register(&client_socket, Token(id),
|
|
156 |
Ready::readable() | Ready::writable(),
|
|
157 |
PollOpt::edge())
|
|
158 |
.ok().expect("could not register socket with event loop");
|
|
159 |
|
|
160 |
let entry = self.clients.vacant_entry();
|
|
161 |
let client = NetworkClient::new(id, client_socket, addr);
|
|
162 |
info!("client {} ({}) added", client.id, client.peer_addr);
|
|
163 |
entry.insert(client);
|
|
164 |
}
|
|
165 |
|
13414
|
166 |
fn flush_server_messages(&mut self) {
|
|
167 |
debug!("{} pending server messages", self.server.output.len());
|
|
168 |
for PendingMessage(destination, msg) in self.server.output.drain(..) {
|
|
169 |
match destination {
|
|
170 |
Destination::ToSelf(id) => {
|
|
171 |
if let Some(ref mut client) = self.clients.get_mut(id) {
|
|
172 |
client.send_msg(msg);
|
|
173 |
self.pending.push_back((id, NetworkClientState::NeedsWrite));
|
|
174 |
}
|
|
175 |
}
|
|
176 |
Destination::ToOthers(id) => {
|
|
177 |
let msg_string = msg.to_raw_protocol();
|
|
178 |
for (client_id, client) in self.clients.iter_mut() {
|
|
179 |
if client_id != id {
|
|
180 |
client.send_string(&msg_string);
|
|
181 |
self.pending.push_back((client_id, NetworkClientState::NeedsWrite));
|
|
182 |
}
|
|
183 |
}
|
|
184 |
}
|
|
185 |
}
|
|
186 |
}
|
|
187 |
}
|
|
188 |
|
13119
|
189 |
pub fn accept_client(&mut self, poll: &Poll) -> io::Result<()> {
|
|
190 |
let (client_socket, addr) = self.listener.accept()?;
|
|
191 |
info!("Connected: {}", addr);
|
|
192 |
|
|
193 |
let client_id = self.server.add_client();
|
|
194 |
self.register_client(poll, client_id, client_socket, addr);
|
|
195 |
self.flush_server_messages();
|
|
196 |
|
|
197 |
Ok(())
|
|
198 |
}
|
|
199 |
|
13414
|
200 |
fn operation_failed(&mut self, poll: &Poll, client_id: ClientId, error: Error, msg: &str) -> io::Result<()> {
|
|
201 |
let addr = if let Some(ref mut client) = self.clients.get_mut(client_id) {
|
|
202 |
client.peer_addr
|
|
203 |
} else {
|
|
204 |
SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 0)
|
|
205 |
};
|
|
206 |
debug!("{}({}): {}", msg, addr, error);
|
|
207 |
self.client_error(poll, client_id)
|
13119
|
208 |
}
|
|
209 |
|
|
210 |
pub fn client_readable(&mut self, poll: &Poll,
|
|
211 |
client_id: ClientId) -> io::Result<()> {
|
13414
|
212 |
let messages =
|
|
213 |
if let Some(ref mut client) = self.clients.get_mut(client_id) {
|
|
214 |
client.read_messages()
|
|
215 |
} else {
|
|
216 |
warn!("invalid readable client: {}", client_id);
|
|
217 |
Ok((Vec::new(), NetworkClientState::Idle))
|
13119
|
218 |
};
|
13414
|
219 |
|
|
220 |
match messages {
|
|
221 |
Ok((messages, state)) => {
|
|
222 |
for message in messages {
|
|
223 |
self.server.handle_msg(client_id, message);
|
|
224 |
}
|
|
225 |
match state {
|
|
226 |
NetworkClientState::NeedsRead =>
|
|
227 |
self.pending.push_back((client_id, state)),
|
|
228 |
NetworkClientState::Closed =>
|
|
229 |
self.client_error(&poll, client_id)?,
|
|
230 |
_ => {}
|
|
231 |
};
|
13119
|
232 |
}
|
13414
|
233 |
Err(e) => self.operation_failed(
|
|
234 |
poll, client_id, e,
|
|
235 |
"Error while reading from client socket")?
|
13119
|
236 |
}
|
|
237 |
|
13414
|
238 |
self.flush_server_messages();
|
|
239 |
|
13119
|
240 |
if !self.server.removed_clients.is_empty() {
|
13414
|
241 |
let ids: Vec<_> = self.server.removed_clients.drain(..).collect();
|
13119
|
242 |
for client_id in ids {
|
|
243 |
self.deregister_client(poll, client_id);
|
|
244 |
}
|
|
245 |
}
|
|
246 |
|
|
247 |
Ok(())
|
|
248 |
}
|
|
249 |
|
|
250 |
pub fn client_writable(&mut self, poll: &Poll,
|
|
251 |
client_id: ClientId) -> io::Result<()> {
|
13414
|
252 |
let result =
|
|
253 |
if let Some(ref mut client) = self.clients.get_mut(client_id) {
|
|
254 |
client.flush()
|
|
255 |
} else {
|
|
256 |
warn!("invalid writable client: {}", client_id);
|
|
257 |
Ok(((), NetworkClientState::Idle))
|
|
258 |
};
|
|
259 |
|
|
260 |
match result {
|
|
261 |
Ok(((), state)) if state == NetworkClientState::NeedsWrite =>
|
|
262 |
self.pending.push_back((client_id, state)),
|
|
263 |
Ok(_) =>
|
|
264 |
{}
|
|
265 |
Err(e) => self.operation_failed(
|
|
266 |
poll, client_id, e,
|
|
267 |
"Error while writing to client socket")?
|
13119
|
268 |
}
|
|
269 |
|
|
270 |
Ok(())
|
|
271 |
}
|
|
272 |
|
|
273 |
pub fn client_error(&mut self, poll: &Poll,
|
|
274 |
client_id: ClientId) -> io::Result<()> {
|
|
275 |
self.deregister_client(poll, client_id);
|
|
276 |
self.server.client_lost(client_id);
|
|
277 |
|
|
278 |
Ok(())
|
|
279 |
}
|
13414
|
280 |
|
|
281 |
pub fn has_pending_operations(&self) -> bool {
|
|
282 |
!self.pending.is_empty()
|
|
283 |
}
|
|
284 |
|
|
285 |
pub fn on_idle(&mut self, poll: &Poll) -> io::Result<()> {
|
|
286 |
while let Some((id, state)) = self.pending.pop_front() {
|
|
287 |
match state {
|
|
288 |
NetworkClientState::NeedsRead =>
|
|
289 |
self.client_readable(poll, id)?,
|
|
290 |
NetworkClientState::NeedsWrite =>
|
|
291 |
self.client_writable(poll, id)?,
|
|
292 |
_ => {}
|
|
293 |
}
|
|
294 |
}
|
|
295 |
Ok(())
|
|
296 |
}
|
13119
|
297 |
}
|