Allow setting identifier for peers

This commit is contained in:
Sofia 2026-07-28 21:23:48 +03:00
parent 3d1c07c2a9
commit 22b08b78dd
3 changed files with 18 additions and 4 deletions

View File

@ -103,7 +103,10 @@ impl<T: std::fmt::Debug + Clone + Serialize + DeserializeOwned + Send + Sync + '
if duration > self.config.ping_interval {
match conn.state {
ConnectionState::ReceivingConnection | ConnectionState::Connecting => {
match self.udp.send_to(*addr, Package::<T>::Hello) {
match self
.udp
.send_to(*addr, Package::<T>::Hello(self.config.identifier.clone()))
{
Ok(bytes) => {
conn.bytes_tx += bytes;
conn.last_sent_ping = now;
@ -255,13 +258,13 @@ impl<T: std::fmt::Debug + Clone + Serialize + DeserializeOwned + Send + Sync + '
let mut messages = Vec::new();
match package {
Package::Hello => {
Package::Hello(identifier) => {
if let Some(conn) = self.connections.get_mut(addr) {
if conn.state == ConnectionState::Connecting {
conn.state = ConnectionState::ConnectingNearlyReady;
}
} else {
if !self.accepting_connections {
if !self.accepting_connections || self.config.identifier != identifier {
self.connections
.insert(*addr, Connection::from(*addr, ConnectionState::Closing));
} else {

View File

@ -53,6 +53,7 @@ pub struct PeerConfig {
timeout: Duration,
disconnect_timeout: Duration,
message_retry: Duration,
identifier: String,
}
impl Default for PeerConfig {
@ -62,6 +63,7 @@ impl Default for PeerConfig {
timeout: Duration::from_millis(2000),
disconnect_timeout: Duration::from_millis(500),
message_retry: Duration::from_millis(100),
identifier: "ExamplePeer".to_string(),
}
}
}
@ -100,6 +102,15 @@ impl PeerConfig {
..self
}
}
/// Sets the identifier string which must be same for both connecting peers
/// in order for connection to succeed.
pub fn with_identifier(self, ident: String) -> PeerConfig {
PeerConfig {
identifier: ident,
..self
}
}
}
pub struct Peer<T: std::fmt::Debug + Clone + Serialize + DeserializeOwned + Send + Sync + 'static> {

View File

@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
pub enum Package<T> {
Hello,
Hello(String),
Ping,
Pong,
Close,