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