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
#![warn(missing_docs, rust_2018_idioms, rust_2018_compatibility)]
#[macro_use]
extern crate log;
#[macro_use]
extern crate serde;
mod bundle;
mod connection;
mod filter;
mod net_event;
mod network_socket;
mod test;
pub use crate::{
bundle::NetworkBundle,
connection::{ConnectionState, NetConnection, NetIdentity},
filter::{FilterConnected, NetFilter},
net_event::NetEvent,
network_socket::NetSocketSystem,
};
use std::net::SocketAddr;
use bincode::{deserialize, serialize, ErrorKind};
use laminar::net::UdpSocket;
use laminar::Packet;
use serde::{de::DeserializeOwned, Serialize};
pub fn send_event<T>(event: &NetEvent<T>, addr: &SocketAddr, socket: &mut UdpSocket)
where
T: Serialize,
{
let ser = serialize(event);
match ser {
Ok(s) => {
let slice = s.as_slice();
match socket.send(&Packet::unreliable(*addr, slice.to_vec())) {
Ok(_qty) => {}
Err(e) => error!("Failed to send data to network socket: {}", e),
}
}
Err(e) => error!("Failed to serialize the event: {}", e),
}
}
fn deserialize_event<T>(data: &[u8]) -> Result<NetEvent<T>, Box<ErrorKind>>
where
T: DeserializeOwned,
{
deserialize::<NetEvent<T>>(data)
}