13119
|
1 |
extern crate slab;
|
|
2 |
|
13414
|
3 |
use std::{
|
|
4 |
io, io::{Error, ErrorKind, Write},
|
|
5 |
net::{SocketAddr, IpAddr, Ipv4Addr},
|
13415
|
6 |
collections::HashSet,
|
13450
|
7 |
mem::{swap, replace}
|
13414
|
8 |
};
|
|
9 |
|
|
10 |
use mio::{
|
|
11 |
net::{TcpStream, TcpListener},
|
|
12 |
Poll, PollOpt, Ready, Token
|
|
13 |
};
|
|
14 |
use netbuf;
|
13119
|
15 |
use slab::Slab;
|
|
16 |
|
13666
|
17 |
use crate::{
|
|
18 |
utils,
|
|
19 |
protocol::{ProtocolDecoder, messages::*}
|
|
20 |
};
|
13414
|
21 |
use super::{
|
13419
|
22 |
server::{HWServer},
|
13450
|
23 |
coretypes::ClientId
|
13414
|
24 |
};
|
|
25 |
|
|
26 |
const MAX_BYTES_PER_READ: usize = 2048;
|
13119
|
27 |
|
13415
|
28 |
#[derive(Hash, Eq, PartialEq, Copy, Clone)]
|
13414
|
29 |
pub enum NetworkClientState {
|
|
30 |
Idle,
|
|
31 |
NeedsWrite,
|
|
32 |
NeedsRead,
|
|
33 |
Closed,
|
|
34 |
}
|
|
35 |
|
|
36 |
type NetworkResult<T> = io::Result<(T, NetworkClientState)>;
|
13119
|
37 |
|
|
38 |
pub struct NetworkClient {
|
|
39 |
id: ClientId,
|
|
40 |
socket: TcpStream,
|
|
41 |
peer_addr: SocketAddr,
|
|
42 |
decoder: ProtocolDecoder,
|
13414
|
43 |
buf_out: netbuf::Buf
|
13119
|
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(),
|
13414
|
51 |
buf_out: netbuf::Buf::new()
|
13119
|
52 |
}
|
|
53 |
}
|
|
54 |
|
13414
|
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) => {
|
13416
|
60 |
debug!("Client {}: read {} bytes", self.id, bytes);
|
13414
|
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)),
|
13415
|
96 |
Ok(_) => (),
|
13414
|
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 |
|
13119
|
109 |
pub fn send_raw_msg(&mut self, msg: &[u8]) {
|
13500
|
110 |
self.buf_out.write_all(msg).unwrap();
|
13119
|
111 |
}
|
|
112 |
|
13500
|
113 |
pub fn send_string(&mut self, msg: &str) {
|
13119
|
114 |
self.send_raw_msg(&msg.as_bytes());
|
|
115 |
}
|
|
116 |
|
13500
|
117 |
pub fn send_msg(&mut self, msg: &HWServerMessage) {
|
13119
|
118 |
self.send_string(&msg.to_raw_protocol());
|
|
119 |
}
|
|
120 |
}
|
|
121 |
|
|
122 |
pub struct NetworkLayer {
|
|
123 |
listener: TcpListener,
|
|
124 |
server: HWServer,
|
13414
|
125 |
clients: Slab<NetworkClient>,
|
13415
|
126 |
pending: HashSet<(ClientId, NetworkClientState)>,
|
|
127 |
pending_cache: Vec<(ClientId, NetworkClientState)>
|
13119
|
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);
|
13415
|
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}
|
13119
|
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;
|
13414
|
146 |
if let Some(ref client) = self.clients.get(id) {
|
13119
|
147 |
poll.deregister(&client.socket)
|
13500
|
148 |
.expect("could not deregister socket");
|
13119
|
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())
|
13500
|
161 |
.expect("could not register socket with event loop");
|
13119
|
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 |
|
13414
|
169 |
fn flush_server_messages(&mut self) {
|
|
170 |
debug!("{} pending server messages", self.server.output.len());
|
13419
|
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));
|
13414
|
178 |
}
|
|
179 |
}
|
|
180 |
}
|
|
181 |
}
|
|
182 |
|
13119
|
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 |
|
13500
|
194 |
fn operation_failed(&mut self, poll: &Poll, client_id: ClientId, error: &Error, msg: &str) -> io::Result<()> {
|
13414
|
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)
|
13119
|
202 |
}
|
|
203 |
|
|
204 |
pub fn client_readable(&mut self, poll: &Poll,
|
|
205 |
client_id: ClientId) -> io::Result<()> {
|
13414
|
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))
|
13119
|
212 |
};
|
13414
|
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 {
|
13415
|
220 |
NetworkClientState::NeedsRead => {
|
|
221 |
self.pending.insert((client_id, state));
|
|
222 |
},
|
13414
|
223 |
NetworkClientState::Closed =>
|
|
224 |
self.client_error(&poll, client_id)?,
|
|
225 |
_ => {}
|
|
226 |
};
|
13119
|
227 |
}
|
13414
|
228 |
Err(e) => self.operation_failed(
|
13500
|
229 |
poll, client_id, &e,
|
13414
|
230 |
"Error while reading from client socket")?
|
13119
|
231 |
}
|
|
232 |
|
13414
|
233 |
self.flush_server_messages();
|
|
234 |
|
13119
|
235 |
if !self.server.removed_clients.is_empty() {
|
13414
|
236 |
let ids: Vec<_> = self.server.removed_clients.drain(..).collect();
|
13119
|
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<()> {
|
13414
|
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 {
|
13415
|
256 |
Ok(((), state)) if state == NetworkClientState::NeedsWrite => {
|
|
257 |
self.pending.insert((client_id, state));
|
|
258 |
},
|
|
259 |
Ok(_) => {}
|
13414
|
260 |
Err(e) => self.operation_failed(
|
13500
|
261 |
poll, client_id, &e,
|
13414
|
262 |
"Error while writing to client socket")?
|
13119
|
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 |
}
|
13414
|
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<()> {
|
13415
|
281 |
if self.has_pending_operations() {
|
13450
|
282 |
let mut cache = replace(&mut self.pending_cache, Vec::new());
|
13415
|
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 |
}
|
13414
|
292 |
}
|
13415
|
293 |
swap(&mut cache, &mut self.pending_cache);
|
13414
|
294 |
}
|
|
295 |
Ok(())
|
|
296 |
}
|
13119
|
297 |
}
|