pub struct NetcodeServer { /* private fields */ }Expand description
A server that can generate packets from connect clients, that are encrypted, or process incoming encrypted packets from clients. The server is agnostic from the transport layer, only consuming and generating bytes that can be transported in any way desired.
Implementations§
Source§impl NetcodeServer
impl NetcodeServer
Sourcepub fn new(config: ServerConfig) -> Self
pub fn new(config: ServerConfig) -> Self
Examples found in repository?
128fn server(addr: SocketAddr, private_key: [u8; NETCODE_KEY_BYTES]) {
129 let current_time = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
130 let config = ServerConfig {
131 current_time,
132 max_clients: 16,
133 protocol_id: PROTOCOL_ID,
134 sockets: vec![ServerSocketConfig::new(vec![addr])],
135 authentication: ServerAuthentication::Secure { private_key },
136 };
137 let mut server: NetcodeServer = NetcodeServer::new(config);
138 let udp_socket = UdpSocket::bind(addr).unwrap();
139 udp_socket.set_nonblocking(true).unwrap();
140 let mut received_messages = vec![];
141 let mut last_updated = Instant::now();
142 let mut buffer = [0u8; NETCODE_MAX_PACKET_BYTES];
143 let mut usernames: HashMap<u64, String> = HashMap::new();
144 loop {
145 server.update(Instant::now() - last_updated);
146 received_messages.clear();
147
148 loop {
149 match udp_socket.recv_from(&mut buffer) {
150 Ok((len, addr)) => {
151 // println!("Received decrypted message {:?} from {}.", &buffer[..len], addr);
152 let server_result = server.process_packet(0, addr, &mut buffer[..len]);
153 handle_server_result(server_result, &udp_socket, &mut received_messages, &mut usernames);
154 }
155 Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => break,
156 Err(e) => panic!("Socket error: {}", e),
157 };
158 }
159
160 for text in received_messages.iter() {
161 for client_id in server.clients_id().iter() {
162 let (_, addr, payload) = server.generate_payload_packet(*client_id, text.as_bytes()).unwrap();
163 udp_socket.send_to(payload, addr).unwrap();
164 }
165 }
166
167 for client_id in server.clients_id().into_iter() {
168 let server_result = server.update_client(client_id);
169 handle_server_result(server_result, &udp_socket, &mut received_messages, &mut usernames);
170 }
171
172 last_updated = Instant::now();
173 thread::sleep(Duration::from_millis(50));
174 }
175}Sourcepub fn addresses(&self, socket_id: usize) -> Vec<SocketAddr>
pub fn addresses(&self, socket_id: usize) -> Vec<SocketAddr>
Gets the public addresses of a specific socket.
Panics if socket_id is out of range.
pub fn current_time(&self) -> Duration
Sourcepub fn user_data(&self, client_id: u64) -> Option<[u8; 256]>
pub fn user_data(&self, client_id: u64) -> Option<[u8; 256]>
Returns the user data from the connected client.
Sourcepub fn time_since_last_received_packet(
&self,
client_id: u64,
) -> Option<Duration>
pub fn time_since_last_received_packet( &self, client_id: u64, ) -> Option<Duration>
Returns the duration since the connected client last received a packet. Usefull to detect users that are timing out.
Sourcepub fn client_addr(&self, client_id: u64) -> Option<(usize, SocketAddr)>
pub fn client_addr(&self, client_id: u64) -> Option<(usize, SocketAddr)>
Returns the client socket id and address if connected.
Sourcepub fn generate_payload_packet<'s>(
&'s mut self,
client_id: u64,
payload: &[u8],
) -> Result<(usize, SocketAddr, &'s mut [u8]), NetcodeError>
pub fn generate_payload_packet<'s>( &'s mut self, client_id: u64, payload: &[u8], ) -> Result<(usize, SocketAddr, &'s mut [u8]), NetcodeError>
Returns an encoded packet payload to be sent to the client.
Examples found in repository?
128fn server(addr: SocketAddr, private_key: [u8; NETCODE_KEY_BYTES]) {
129 let current_time = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
130 let config = ServerConfig {
131 current_time,
132 max_clients: 16,
133 protocol_id: PROTOCOL_ID,
134 sockets: vec![ServerSocketConfig::new(vec![addr])],
135 authentication: ServerAuthentication::Secure { private_key },
136 };
137 let mut server: NetcodeServer = NetcodeServer::new(config);
138 let udp_socket = UdpSocket::bind(addr).unwrap();
139 udp_socket.set_nonblocking(true).unwrap();
140 let mut received_messages = vec![];
141 let mut last_updated = Instant::now();
142 let mut buffer = [0u8; NETCODE_MAX_PACKET_BYTES];
143 let mut usernames: HashMap<u64, String> = HashMap::new();
144 loop {
145 server.update(Instant::now() - last_updated);
146 received_messages.clear();
147
148 loop {
149 match udp_socket.recv_from(&mut buffer) {
150 Ok((len, addr)) => {
151 // println!("Received decrypted message {:?} from {}.", &buffer[..len], addr);
152 let server_result = server.process_packet(0, addr, &mut buffer[..len]);
153 handle_server_result(server_result, &udp_socket, &mut received_messages, &mut usernames);
154 }
155 Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => break,
156 Err(e) => panic!("Socket error: {}", e),
157 };
158 }
159
160 for text in received_messages.iter() {
161 for client_id in server.clients_id().iter() {
162 let (_, addr, payload) = server.generate_payload_packet(*client_id, text.as_bytes()).unwrap();
163 udp_socket.send_to(payload, addr).unwrap();
164 }
165 }
166
167 for client_id in server.clients_id().into_iter() {
168 let server_result = server.update_client(client_id);
169 handle_server_result(server_result, &udp_socket, &mut received_messages, &mut usernames);
170 }
171
172 last_updated = Instant::now();
173 thread::sleep(Duration::from_millis(50));
174 }
175}Sourcepub fn process_packet<'a, 's>(
&'s mut self,
socket_id: usize,
addr: SocketAddr,
buffer: &'a mut [u8],
) -> ServerResult<'a, 's>
pub fn process_packet<'a, 's>( &'s mut self, socket_id: usize, addr: SocketAddr, buffer: &'a mut [u8], ) -> ServerResult<'a, 's>
Process an packet from the especifed address. Returns a server result, check out ServerResult.
Examples found in repository?
128fn server(addr: SocketAddr, private_key: [u8; NETCODE_KEY_BYTES]) {
129 let current_time = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
130 let config = ServerConfig {
131 current_time,
132 max_clients: 16,
133 protocol_id: PROTOCOL_ID,
134 sockets: vec![ServerSocketConfig::new(vec![addr])],
135 authentication: ServerAuthentication::Secure { private_key },
136 };
137 let mut server: NetcodeServer = NetcodeServer::new(config);
138 let udp_socket = UdpSocket::bind(addr).unwrap();
139 udp_socket.set_nonblocking(true).unwrap();
140 let mut received_messages = vec![];
141 let mut last_updated = Instant::now();
142 let mut buffer = [0u8; NETCODE_MAX_PACKET_BYTES];
143 let mut usernames: HashMap<u64, String> = HashMap::new();
144 loop {
145 server.update(Instant::now() - last_updated);
146 received_messages.clear();
147
148 loop {
149 match udp_socket.recv_from(&mut buffer) {
150 Ok((len, addr)) => {
151 // println!("Received decrypted message {:?} from {}.", &buffer[..len], addr);
152 let server_result = server.process_packet(0, addr, &mut buffer[..len]);
153 handle_server_result(server_result, &udp_socket, &mut received_messages, &mut usernames);
154 }
155 Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => break,
156 Err(e) => panic!("Socket error: {}", e),
157 };
158 }
159
160 for text in received_messages.iter() {
161 for client_id in server.clients_id().iter() {
162 let (_, addr, payload) = server.generate_payload_packet(*client_id, text.as_bytes()).unwrap();
163 udp_socket.send_to(payload, addr).unwrap();
164 }
165 }
166
167 for client_id in server.clients_id().into_iter() {
168 let server_result = server.update_client(client_id);
169 handle_server_result(server_result, &udp_socket, &mut received_messages, &mut usernames);
170 }
171
172 last_updated = Instant::now();
173 thread::sleep(Duration::from_millis(50));
174 }
175}pub fn clients_slot(&self) -> Vec<usize>
Sourcepub fn clients_id_iter(&self) -> impl Iterator<Item = u64> + '_
pub fn clients_id_iter(&self) -> impl Iterator<Item = u64> + '_
Returns the ids from the connected clients (iterator).
Sourcepub fn clients_id(&self) -> Vec<u64>
pub fn clients_id(&self) -> Vec<u64>
Returns the ids from the connected clients.
Examples found in repository?
128fn server(addr: SocketAddr, private_key: [u8; NETCODE_KEY_BYTES]) {
129 let current_time = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
130 let config = ServerConfig {
131 current_time,
132 max_clients: 16,
133 protocol_id: PROTOCOL_ID,
134 sockets: vec![ServerSocketConfig::new(vec![addr])],
135 authentication: ServerAuthentication::Secure { private_key },
136 };
137 let mut server: NetcodeServer = NetcodeServer::new(config);
138 let udp_socket = UdpSocket::bind(addr).unwrap();
139 udp_socket.set_nonblocking(true).unwrap();
140 let mut received_messages = vec![];
141 let mut last_updated = Instant::now();
142 let mut buffer = [0u8; NETCODE_MAX_PACKET_BYTES];
143 let mut usernames: HashMap<u64, String> = HashMap::new();
144 loop {
145 server.update(Instant::now() - last_updated);
146 received_messages.clear();
147
148 loop {
149 match udp_socket.recv_from(&mut buffer) {
150 Ok((len, addr)) => {
151 // println!("Received decrypted message {:?} from {}.", &buffer[..len], addr);
152 let server_result = server.process_packet(0, addr, &mut buffer[..len]);
153 handle_server_result(server_result, &udp_socket, &mut received_messages, &mut usernames);
154 }
155 Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => break,
156 Err(e) => panic!("Socket error: {}", e),
157 };
158 }
159
160 for text in received_messages.iter() {
161 for client_id in server.clients_id().iter() {
162 let (_, addr, payload) = server.generate_payload_packet(*client_id, text.as_bytes()).unwrap();
163 udp_socket.send_to(payload, addr).unwrap();
164 }
165 }
166
167 for client_id in server.clients_id().into_iter() {
168 let server_result = server.update_client(client_id);
169 handle_server_result(server_result, &udp_socket, &mut received_messages, &mut usernames);
170 }
171
172 last_updated = Instant::now();
173 thread::sleep(Duration::from_millis(50));
174 }
175}Sourcepub fn max_clients(&self) -> usize
pub fn max_clients(&self) -> usize
Returns the maximum number of clients that can be connected.
Sourcepub fn set_max_clients(&mut self, max_clients: usize)
pub fn set_max_clients(&mut self, max_clients: usize)
Update the maximum numbers of clients that can be connected
Changing the max_clients to a lower value than the current number of connect clients
does not disconnect clients. So NetcodeServer::connected_clients() can return a
higher value than NetcodeServer::max_clients().
Sourcepub fn connected_clients(&self) -> usize
pub fn connected_clients(&self) -> usize
Returns current number of clients connected.
Sourcepub fn update(&mut self, duration: Duration)
pub fn update(&mut self, duration: Duration)
Advance the server current time, and remove any pending connections that have expired.
Examples found in repository?
128fn server(addr: SocketAddr, private_key: [u8; NETCODE_KEY_BYTES]) {
129 let current_time = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
130 let config = ServerConfig {
131 current_time,
132 max_clients: 16,
133 protocol_id: PROTOCOL_ID,
134 sockets: vec![ServerSocketConfig::new(vec![addr])],
135 authentication: ServerAuthentication::Secure { private_key },
136 };
137 let mut server: NetcodeServer = NetcodeServer::new(config);
138 let udp_socket = UdpSocket::bind(addr).unwrap();
139 udp_socket.set_nonblocking(true).unwrap();
140 let mut received_messages = vec![];
141 let mut last_updated = Instant::now();
142 let mut buffer = [0u8; NETCODE_MAX_PACKET_BYTES];
143 let mut usernames: HashMap<u64, String> = HashMap::new();
144 loop {
145 server.update(Instant::now() - last_updated);
146 received_messages.clear();
147
148 loop {
149 match udp_socket.recv_from(&mut buffer) {
150 Ok((len, addr)) => {
151 // println!("Received decrypted message {:?} from {}.", &buffer[..len], addr);
152 let server_result = server.process_packet(0, addr, &mut buffer[..len]);
153 handle_server_result(server_result, &udp_socket, &mut received_messages, &mut usernames);
154 }
155 Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => break,
156 Err(e) => panic!("Socket error: {}", e),
157 };
158 }
159
160 for text in received_messages.iter() {
161 for client_id in server.clients_id().iter() {
162 let (_, addr, payload) = server.generate_payload_packet(*client_id, text.as_bytes()).unwrap();
163 udp_socket.send_to(payload, addr).unwrap();
164 }
165 }
166
167 for client_id in server.clients_id().into_iter() {
168 let server_result = server.update_client(client_id);
169 handle_server_result(server_result, &udp_socket, &mut received_messages, &mut usernames);
170 }
171
172 last_updated = Instant::now();
173 thread::sleep(Duration::from_millis(50));
174 }
175}Sourcepub fn update_client(&mut self, client_id: u64) -> ServerResult<'_, '_>
pub fn update_client(&mut self, client_id: u64) -> ServerResult<'_, '_>
Updates the client, returns a ServerResult.
§Example
for client_id in server.clients_id().into_iter() {
match server.update_client(client_id) {
ServerResult::PacketToSend { payload, socket_id, addr } => send_to(payload, socket_id, addr),
_ => { /* ... */ }
}
}Examples found in repository?
128fn server(addr: SocketAddr, private_key: [u8; NETCODE_KEY_BYTES]) {
129 let current_time = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
130 let config = ServerConfig {
131 current_time,
132 max_clients: 16,
133 protocol_id: PROTOCOL_ID,
134 sockets: vec![ServerSocketConfig::new(vec![addr])],
135 authentication: ServerAuthentication::Secure { private_key },
136 };
137 let mut server: NetcodeServer = NetcodeServer::new(config);
138 let udp_socket = UdpSocket::bind(addr).unwrap();
139 udp_socket.set_nonblocking(true).unwrap();
140 let mut received_messages = vec![];
141 let mut last_updated = Instant::now();
142 let mut buffer = [0u8; NETCODE_MAX_PACKET_BYTES];
143 let mut usernames: HashMap<u64, String> = HashMap::new();
144 loop {
145 server.update(Instant::now() - last_updated);
146 received_messages.clear();
147
148 loop {
149 match udp_socket.recv_from(&mut buffer) {
150 Ok((len, addr)) => {
151 // println!("Received decrypted message {:?} from {}.", &buffer[..len], addr);
152 let server_result = server.process_packet(0, addr, &mut buffer[..len]);
153 handle_server_result(server_result, &udp_socket, &mut received_messages, &mut usernames);
154 }
155 Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => break,
156 Err(e) => panic!("Socket error: {}", e),
157 };
158 }
159
160 for text in received_messages.iter() {
161 for client_id in server.clients_id().iter() {
162 let (_, addr, payload) = server.generate_payload_packet(*client_id, text.as_bytes()).unwrap();
163 udp_socket.send_to(payload, addr).unwrap();
164 }
165 }
166
167 for client_id in server.clients_id().into_iter() {
168 let server_result = server.update_client(client_id);
169 handle_server_result(server_result, &udp_socket, &mut received_messages, &mut usernames);
170 }
171
172 last_updated = Instant::now();
173 thread::sleep(Duration::from_millis(50));
174 }
175}pub fn is_client_connected(&self, client_id: u64) -> bool
Sourcepub fn disconnect(&mut self, client_id: u64) -> ServerResult<'_, '_>
pub fn disconnect(&mut self, client_id: u64) -> ServerResult<'_, '_>
Disconnect an client and returns its address and a disconnect packet to be sent to them.