1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
use crate::{client::NativeClient, utils::DoOnDrop};
use network::{
    client::{Client, ClientID, ClientState, MessageID},
    server::{Server, ServerID, ServerState},
};
use std::{
    collections::{HashMap, VecDeque},
    io::ErrorKind,
    mem::replace,
    net::TcpListener,
    ops::Range,
    sync::{Arc, Mutex},
    thread::{sleep, Builder as ThreadBuilder, JoinHandle},
    time::Duration,
};

const LISTENER_SLEEP_MS: u64 = 10;

type MsgData = (ClientID, MessageID, Vec<u8>);

pub struct NativeServer {
    id: ServerID,
    state: Arc<Mutex<ServerState>>,
    clients: Arc<Mutex<HashMap<ClientID, NativeClient>>>,
    clients_ids_cached: Vec<ClientID>,
    messages: VecDeque<MsgData>,
    thread: Option<JoinHandle<()>>,
}

impl Drop for NativeServer {
    fn drop(&mut self) {
        self.cleanup();
    }
}

impl NativeServer {
    fn cleanup(&mut self) {
        {
            *self.state.lock().unwrap() = ServerState::Closed;
        }
        let thread = replace(&mut self.thread, None);
        if let Some(thread) = thread {
            thread.join().unwrap();
        }
    }
}

impl Server for NativeServer {
    fn open(url: &str) -> Option<Self> {
        let sid = ServerID::default();
        let url = url.to_owned();
        let state = Arc::new(Mutex::new(ServerState::Starting));
        let state2 = state.clone();
        let clients = Arc::new(Mutex::new(HashMap::default()));
        let clients2 = clients.clone();
        let thread = Some(
            ThreadBuilder::new()
                .name(format!("Server: {:?}", sid))
                .spawn(move || {
                    let state3 = state2.clone();
                    let _ = DoOnDrop::new(move || *state3.lock().unwrap() = ServerState::Closed);
                    let listener = TcpListener::bind(&url).unwrap();
                    listener.set_nonblocking(true).unwrap_or_else(|_| {
                        panic!(
                            "Server {:?} cannot set non-blocking listening on: {}",
                            sid, &url
                        )
                    });
                    {
                        *state2.lock().unwrap() = ServerState::Open;
                    }
                    for stream in listener.incoming() {
                        {
                            if *state2.lock().unwrap() == ServerState::Closed {
                                break;
                            }
                        }
                        match stream {
                            Ok(stream) => {
                                let client = NativeClient::from(stream);
                                let id = client.id();
                                clients2.lock().unwrap().insert(id, client);
                            }
                            Err(ref e) if e.kind() == ErrorKind::WouldBlock => {
                                sleep(Duration::from_millis(LISTENER_SLEEP_MS));
                            }
                            Err(ref e) if e.kind() == ErrorKind::UnexpectedEof => {
                                break;
                            }
                            Err(e) => {
                                panic!("Server {:?} listener {} got IO error: {}", sid, &url, e)
                            }
                        }
                    }
                    {
                        *state2.lock().unwrap() = ServerState::Closed;
                    }
                })
                .unwrap(),
        );
        Some(Self {
            id: sid,
            state,
            clients,
            clients_ids_cached: vec![],
            messages: Default::default(),
            thread,
        })
    }

    fn close(mut self) -> Self {
        self.cleanup();
        self
    }

    fn id(&self) -> ServerID {
        self.id
    }

    fn state(&self) -> ServerState {
        *self.state.lock().unwrap()
    }

    fn clients(&self) -> &[ClientID] {
        &self.clients_ids_cached
    }

    fn disconnect(&mut self, id: ClientID) {
        let mut clients = self.clients.lock().unwrap();
        if let Some(client) = clients.remove(&id) {
            client.close();
        }
    }

    fn disconnect_all(&mut self) {
        let mut clients = self.clients.lock().unwrap();
        for (_, client) in clients.drain() {
            client.close();
        }
    }

    fn send(&mut self, id: ClientID, msg_id: MessageID, data: &[u8]) -> Option<Range<usize>> {
        if self.state() != ServerState::Open {
            return None;
        }
        let mut clients = self.clients.lock().unwrap();
        if let Some(client) = clients.get_mut(&id) {
            if let Some(size) = client.send(msg_id, data) {
                return Some(size);
            }
        }
        None
    }

    fn send_all(&mut self, id: MessageID, data: &[u8]) {
        if self.state() != ServerState::Open {
            return;
        }
        let mut clients = self.clients.lock().unwrap();
        for client in clients.values_mut() {
            drop(client.send(id, data));
        }
    }

    fn read(&mut self) -> Option<(ClientID, MessageID, Vec<u8>)> {
        self.messages.pop_front()
    }

    fn read_all(&mut self) -> Vec<MsgData> {
        self.messages.drain(..).collect()
    }

    fn process(&mut self) {
        let mut clients = self.clients.lock().unwrap();
        for (id, client) in clients.iter_mut() {
            self.messages.extend(
                client
                    .read_all()
                    .into_iter()
                    .map(|(mid, data)| (*id, mid, data)),
            );
        }
        clients.retain(|_, client| client.state() != ClientState::Closed);
        self.clients_ids_cached.clear();
        for id in clients.keys() {
            self.clients_ids_cached.push(*id);
        }
    }
}