Skip to main content

karyon_net/transports/
udp.rs

1use std::net::SocketAddr;
2use std::sync::Arc;
3
4use karyon_core::async_runtime::net::UdpSocket;
5
6use crate::{Endpoint, Result};
7
8/// UDP config.
9#[derive(Default)]
10pub struct UdpConfig {}
11
12/// Raw UDP connection. Sends and receives raw bytes with addresses.
13pub struct UdpConn {
14    socket: Arc<UdpSocket>,
15}
16
17impl UdpConn {
18    /// Send raw bytes to an address.
19    pub async fn send_to(&self, buf: &[u8], addr: SocketAddr) -> Result<usize> {
20        let n = self.socket.send_to(buf, addr).await?;
21        Ok(n)
22    }
23
24    /// Receive raw bytes. Returns (bytes_read, sender address).
25    pub async fn recv_from(&self, buf: &mut [u8]) -> Result<(usize, SocketAddr)> {
26        let (n, addr) = self.socket.recv_from(buf).await?;
27        Ok((n, addr))
28    }
29
30    /// Local address this socket is bound to.
31    pub fn local_endpoint(&self) -> Result<Endpoint> {
32        Ok(Endpoint::new_udp_addr(self.socket.local_addr()?))
33    }
34
35    /// Peer address (if connected via dial).
36    pub fn peer_endpoint(&self) -> Result<Endpoint> {
37        Ok(Endpoint::new_udp_addr(self.socket.peer_addr()?))
38    }
39}
40
41/// Connect to a UDP endpoint.
42pub async fn dial(endpoint: &Endpoint, _config: UdpConfig) -> Result<UdpConn> {
43    let addr = SocketAddr::try_from(endpoint.clone())?;
44    let socket = UdpSocket::bind("[::]:0").await?;
45    socket.connect(addr).await?;
46    Ok(UdpConn {
47        socket: Arc::new(socket),
48    })
49}
50
51/// Listen on a UDP endpoint.
52pub async fn listen(endpoint: &Endpoint, _config: UdpConfig) -> Result<UdpConn> {
53    let addr = SocketAddr::try_from(endpoint.clone())?;
54    let socket = UdpSocket::bind(addr).await?;
55    Ok(UdpConn {
56        socket: Arc::new(socket),
57    })
58}