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
use crate::network_adapter::{self, Connection};
use serde::{Serialize, Deserialize};
use std::sync::{Arc, atomic::{AtomicBool, Ordering}};
use std::net::{SocketAddr};
use std::thread::{self, JoinHandle};
use std::fmt::{self};
use std::time::{Duration};
pub type Endpoint = usize;
const NETWORK_SAMPLING_TIMEOUT: u64 = 50;
#[derive(Debug, Clone, Copy)]
pub enum TransportProtocol {
Tcp,
Udp,
}
#[derive(Debug)]
pub enum NetEvent<InMessage>
where InMessage: for<'b> Deserialize<'b> + Send + 'static {
Message(Endpoint, InMessage),
AddedEndpoint(Endpoint, SocketAddr),
RemovedEndpoint(Endpoint),
}
impl fmt::Display for TransportProtocol {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", format!("{:?}", self).to_lowercase())
}
}
pub struct NetworkManager {
network_event_thread: Option<JoinHandle<()>>,
network_thread_running: Arc<AtomicBool>,
network_controller: network_adapter::Controller,
output_buffer: Vec<u8>,
}
impl<'a> NetworkManager {
pub fn new<InMessage, C>(event_callback: C) -> NetworkManager
where InMessage: for<'b> Deserialize<'b> + Send + 'static,
C: Fn(NetEvent<InMessage>) + Send + 'static {
let (network_controller, mut network_receiver) = network_adapter::adapter();
let network_thread_running = Arc::new(AtomicBool::new(true));
let running = network_thread_running.clone();
let network_event_thread = thread::spawn(move || {
let timeout = Duration::from_millis(NETWORK_SAMPLING_TIMEOUT);
while running.load(Ordering::Relaxed) {
network_receiver.receive(Some(timeout), |store, endpoint, event| {
let net_event = match event {
network_adapter::Event::Connection(address) => {
log::trace!("Connected endpoint {}", address);
NetEvent::AddedEndpoint(endpoint, address)
},
network_adapter::Event::Data(data) => {
log::trace!("Message received from {}", store.connection_remote_address(endpoint).unwrap());
let message: InMessage = bincode::deserialize(&data[..]).unwrap();
NetEvent::Message(endpoint, message)
},
network_adapter::Event::Disconnection => {
log::trace!("Disconnected endpoint {}", store.connection_remote_address(endpoint).unwrap());
NetEvent::RemovedEndpoint(endpoint)
},
};
event_callback(net_event);
});
}
});
NetworkManager {
network_event_thread: Some(network_event_thread),
network_thread_running,
network_controller,
output_buffer: Vec::new()
}
}
pub fn connect(&mut self, addr: SocketAddr, transport: TransportProtocol) -> Option<(Endpoint, SocketAddr)> {
match transport {
TransportProtocol::Tcp => Connection::new_tcp_stream(addr),
TransportProtocol::Udp => Connection::new_udp_socket(addr),
}
.ok()
.map(|connection| {
let address = connection.local_address();
let endpoint = self.network_controller.add_connection(connection);
(endpoint, address)
})
}
pub fn listen(&mut self, addr: SocketAddr, transport: TransportProtocol) -> Option<(Endpoint, SocketAddr)> {
match transport {
TransportProtocol::Tcp => Connection::new_tcp_listener(addr),
TransportProtocol::Udp => Connection::new_udp_listener(addr),
}
.ok()
.map(|connection| {
let address = connection.local_address();
let endpoint = self.network_controller.add_connection(connection);
(endpoint, address)
})
}
pub fn endpoint_local_address(&mut self, endpoint: Endpoint) -> Option<SocketAddr> {
self.network_controller.connection_local_address(endpoint)
}
pub fn endpoint_remote_address(&mut self, endpoint: Endpoint) -> Option<SocketAddr> {
self.network_controller.connection_remote_address(endpoint)
}
pub fn remove_endpoint(&mut self, endpoint: Endpoint) -> Option<()> {
self.network_controller.remove_connection(endpoint)
}
pub fn send<OutMessage>(&mut self, endpoint: Endpoint, message: OutMessage) -> Option<()>
where OutMessage: Serialize {
bincode::serialize_into(&mut self.output_buffer, &message).unwrap();
let result = self.network_controller.send(endpoint, &self.output_buffer);
self.output_buffer.clear();
if let Some(_) = result {
log::trace!("Message sent to {}", self.network_controller.connection_remote_address(endpoint).unwrap());
}
result
}
pub fn send_all<'b, OutMessage>(&mut self, endpoints: impl IntoIterator<Item=&'b Endpoint>, message: OutMessage) -> Result<(), Vec<Endpoint>>
where OutMessage: Serialize {
let mut unrecognized_ids = Vec::new();
bincode::serialize_into(&mut self.output_buffer, &message).unwrap();
for endpoint in endpoints {
match self.network_controller.send(*endpoint, &self.output_buffer) {
Some(_) => log::trace!("Message sent to {}", self.network_controller.connection_remote_address(*endpoint).unwrap()),
None => unrecognized_ids.push(*endpoint)
}
}
self.output_buffer.clear();
if unrecognized_ids.is_empty() { Ok(()) } else { Err(unrecognized_ids) }
}
}
impl Drop for NetworkManager {
fn drop(&mut self) {
self.network_thread_running.store(false, Ordering::Relaxed);
self.network_event_thread.take().unwrap().join().unwrap();
}
}