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