Skip to main content

UdpServer

Struct UdpServer 

Source
pub struct UdpServer<const N: usize> { /* private fields */ }
Expand description

Multi-peer UDP server adapter.

Implementations§

Source§

impl<const N: usize> UdpServer<N>

Source

pub async fn bind<A>(local: A) -> Result<Self>
where A: ToSocketAddrs,

Binds a UDP server socket using default MSRT config.

Source

pub async fn bind_with_config<A>(local: A, config: EngineConfig) -> Result<Self>
where A: ToSocketAddrs,

Binds a UDP server socket using config.

Examples found in repository?
examples/server.rs (line 18)
14async fn main() -> msrt_udp::Result<()> {
15    let bind = env::args()
16        .nth(1)
17        .unwrap_or_else(|| DEFAULT_BIND.to_string());
18    let mut server = UdpServer::<16>::bind_with_config(&bind, demo_config()).await?;
19    println!("server listening on {}", server.local_addr()?);
20
21    let mut next_idle_sweep = Instant::now() + Duration::from_secs(1);
22
23    loop {
24        match server.tick().await? {
25            UdpServerEvent::Message { peer, message } if message.as_bytes() != [0] => {
26                let text = String::from_utf8_lossy(message.as_bytes());
27                println!("{peer}: {text}");
28                let reply = format!("echo from server: {text}");
29                let _ = server.send_to(peer, reply.as_bytes())?;
30            }
31            UdpServerEvent::Message { .. } | UdpServerEvent::Idle => {}
32            UdpServerEvent::SendFailed { peer, failed } => {
33                println!("{peer}: send failed: {failed:?}; disconnecting peer");
34                server.disconnect(peer);
35            }
36        }
37
38        if next_idle_sweep <= Instant::now() {
39            let disconnected = server.disconnect_idle(IDLE_TIMEOUT.as_millis() as u64);
40            if disconnected > 0 {
41                println!("disconnected {disconnected} idle peer(s)");
42            }
43            next_idle_sweep = Instant::now() + Duration::from_secs(1);
44        }
45
46        sleep(LOOP_SLEEP).await;
47    }
48}
Source

pub fn from_socket(socket: UdpSocket, config: EngineConfig) -> Self

Creates a server from an existing UDP socket.

Source

pub fn local_addr(&self) -> Result<SocketAddr>

Returns the local socket address.

Examples found in repository?
examples/server.rs (line 19)
14async fn main() -> msrt_udp::Result<()> {
15    let bind = env::args()
16        .nth(1)
17        .unwrap_or_else(|| DEFAULT_BIND.to_string());
18    let mut server = UdpServer::<16>::bind_with_config(&bind, demo_config()).await?;
19    println!("server listening on {}", server.local_addr()?);
20
21    let mut next_idle_sweep = Instant::now() + Duration::from_secs(1);
22
23    loop {
24        match server.tick().await? {
25            UdpServerEvent::Message { peer, message } if message.as_bytes() != [0] => {
26                let text = String::from_utf8_lossy(message.as_bytes());
27                println!("{peer}: {text}");
28                let reply = format!("echo from server: {text}");
29                let _ = server.send_to(peer, reply.as_bytes())?;
30            }
31            UdpServerEvent::Message { .. } | UdpServerEvent::Idle => {}
32            UdpServerEvent::SendFailed { peer, failed } => {
33                println!("{peer}: send failed: {failed:?}; disconnecting peer");
34                server.disconnect(peer);
35            }
36        }
37
38        if next_idle_sweep <= Instant::now() {
39            let disconnected = server.disconnect_idle(IDLE_TIMEOUT.as_millis() as u64);
40            if disconnected > 0 {
41                println!("disconnected {disconnected} idle peer(s)");
42            }
43            next_idle_sweep = Instant::now() + Duration::from_secs(1);
44        }
45
46        sleep(LOOP_SLEEP).await;
47    }
48}
Source

pub const fn socket(&self) -> &UdpSocket

Returns a shared reference to the UDP socket.

Source

pub fn socket_mut(&mut self) -> &mut UdpSocket

Returns a mutable reference to the UDP socket.

Source

pub fn into_socket(self) -> UdpSocket

Consumes the adapter and returns the UDP socket.

Source

pub fn peer_state(&mut self, peer: SocketAddr) -> Option<PeerState>

Returns the peer state for peer.

Source

pub fn peers(&self) -> impl Iterator<Item = SocketAddr> + '_

Returns the currently accepted peers.

Source

pub fn send_to(&mut self, peer: SocketAddr, message: &[u8]) -> Result<bool>

Queues an application message for peer.

Examples found in repository?
examples/server.rs (line 29)
14async fn main() -> msrt_udp::Result<()> {
15    let bind = env::args()
16        .nth(1)
17        .unwrap_or_else(|| DEFAULT_BIND.to_string());
18    let mut server = UdpServer::<16>::bind_with_config(&bind, demo_config()).await?;
19    println!("server listening on {}", server.local_addr()?);
20
21    let mut next_idle_sweep = Instant::now() + Duration::from_secs(1);
22
23    loop {
24        match server.tick().await? {
25            UdpServerEvent::Message { peer, message } if message.as_bytes() != [0] => {
26                let text = String::from_utf8_lossy(message.as_bytes());
27                println!("{peer}: {text}");
28                let reply = format!("echo from server: {text}");
29                let _ = server.send_to(peer, reply.as_bytes())?;
30            }
31            UdpServerEvent::Message { .. } | UdpServerEvent::Idle => {}
32            UdpServerEvent::SendFailed { peer, failed } => {
33                println!("{peer}: send failed: {failed:?}; disconnecting peer");
34                server.disconnect(peer);
35            }
36        }
37
38        if next_idle_sweep <= Instant::now() {
39            let disconnected = server.disconnect_idle(IDLE_TIMEOUT.as_millis() as u64);
40            if disconnected > 0 {
41                println!("disconnected {disconnected} idle peer(s)");
42            }
43            next_idle_sweep = Instant::now() + Duration::from_secs(1);
44        }
45
46        sleep(LOOP_SLEEP).await;
47    }
48}
Source

pub fn disconnect(&mut self, peer: SocketAddr) -> bool

Disconnects a peer and frees its server slot.

Examples found in repository?
examples/server.rs (line 34)
14async fn main() -> msrt_udp::Result<()> {
15    let bind = env::args()
16        .nth(1)
17        .unwrap_or_else(|| DEFAULT_BIND.to_string());
18    let mut server = UdpServer::<16>::bind_with_config(&bind, demo_config()).await?;
19    println!("server listening on {}", server.local_addr()?);
20
21    let mut next_idle_sweep = Instant::now() + Duration::from_secs(1);
22
23    loop {
24        match server.tick().await? {
25            UdpServerEvent::Message { peer, message } if message.as_bytes() != [0] => {
26                let text = String::from_utf8_lossy(message.as_bytes());
27                println!("{peer}: {text}");
28                let reply = format!("echo from server: {text}");
29                let _ = server.send_to(peer, reply.as_bytes())?;
30            }
31            UdpServerEvent::Message { .. } | UdpServerEvent::Idle => {}
32            UdpServerEvent::SendFailed { peer, failed } => {
33                println!("{peer}: send failed: {failed:?}; disconnecting peer");
34                server.disconnect(peer);
35            }
36        }
37
38        if next_idle_sweep <= Instant::now() {
39            let disconnected = server.disconnect_idle(IDLE_TIMEOUT.as_millis() as u64);
40            if disconnected > 0 {
41                println!("disconnected {disconnected} idle peer(s)");
42            }
43            next_idle_sweep = Instant::now() + Duration::from_secs(1);
44        }
45
46        sleep(LOOP_SLEEP).await;
47    }
48}
Source

pub fn disconnect_idle(&mut self, timeout_ms: u64) -> usize

Disconnects every peer idle for at least timeout_ms.

Examples found in repository?
examples/server.rs (line 39)
14async fn main() -> msrt_udp::Result<()> {
15    let bind = env::args()
16        .nth(1)
17        .unwrap_or_else(|| DEFAULT_BIND.to_string());
18    let mut server = UdpServer::<16>::bind_with_config(&bind, demo_config()).await?;
19    println!("server listening on {}", server.local_addr()?);
20
21    let mut next_idle_sweep = Instant::now() + Duration::from_secs(1);
22
23    loop {
24        match server.tick().await? {
25            UdpServerEvent::Message { peer, message } if message.as_bytes() != [0] => {
26                let text = String::from_utf8_lossy(message.as_bytes());
27                println!("{peer}: {text}");
28                let reply = format!("echo from server: {text}");
29                let _ = server.send_to(peer, reply.as_bytes())?;
30            }
31            UdpServerEvent::Message { .. } | UdpServerEvent::Idle => {}
32            UdpServerEvent::SendFailed { peer, failed } => {
33                println!("{peer}: send failed: {failed:?}; disconnecting peer");
34                server.disconnect(peer);
35            }
36        }
37
38        if next_idle_sweep <= Instant::now() {
39            let disconnected = server.disconnect_idle(IDLE_TIMEOUT.as_millis() as u64);
40            if disconnected > 0 {
41                println!("disconnected {disconnected} idle peer(s)");
42            }
43            next_idle_sweep = Instant::now() + Duration::from_secs(1);
44        }
45
46        sleep(LOOP_SLEEP).await;
47    }
48}
Source

pub fn receive_available(&mut self) -> Result<usize>

Receives currently available UDP datagrams and feeds them into MSRT.

Unknown peers are accepted automatically. If the fixed-capacity peer table is full, Error::Accept is returned.

Source

pub async fn poll(&mut self) -> Result<UdpServerEvent>

Polls one adapter event and sends pending UDP datagrams.

Source

pub async fn tick(&mut self) -> Result<UdpServerEvent>

Runs receive_available followed by poll.

Examples found in repository?
examples/server.rs (line 24)
14async fn main() -> msrt_udp::Result<()> {
15    let bind = env::args()
16        .nth(1)
17        .unwrap_or_else(|| DEFAULT_BIND.to_string());
18    let mut server = UdpServer::<16>::bind_with_config(&bind, demo_config()).await?;
19    println!("server listening on {}", server.local_addr()?);
20
21    let mut next_idle_sweep = Instant::now() + Duration::from_secs(1);
22
23    loop {
24        match server.tick().await? {
25            UdpServerEvent::Message { peer, message } if message.as_bytes() != [0] => {
26                let text = String::from_utf8_lossy(message.as_bytes());
27                println!("{peer}: {text}");
28                let reply = format!("echo from server: {text}");
29                let _ = server.send_to(peer, reply.as_bytes())?;
30            }
31            UdpServerEvent::Message { .. } | UdpServerEvent::Idle => {}
32            UdpServerEvent::SendFailed { peer, failed } => {
33                println!("{peer}: send failed: {failed:?}; disconnecting peer");
34                server.disconnect(peer);
35            }
36        }
37
38        if next_idle_sweep <= Instant::now() {
39            let disconnected = server.disconnect_idle(IDLE_TIMEOUT.as_millis() as u64);
40            if disconnected > 0 {
41                println!("disconnected {disconnected} idle peer(s)");
42            }
43            next_idle_sweep = Instant::now() + Duration::from_secs(1);
44        }
45
46        sleep(LOOP_SLEEP).await;
47    }
48}

Trait Implementations§

Source§

impl<const N: usize> Debug for UdpServer<N>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<const N: usize> !Freeze for UdpServer<N>

§

impl<const N: usize> RefUnwindSafe for UdpServer<N>

§

impl<const N: usize> Send for UdpServer<N>

§

impl<const N: usize> Sync for UdpServer<N>

§

impl<const N: usize> Unpin for UdpServer<N>

§

impl<const N: usize> UnsafeUnpin for UdpServer<N>

§

impl<const N: usize> UnwindSafe for UdpServer<N>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.