karyon_net/transports/
udp.rs1use std::net::SocketAddr;
2use std::sync::Arc;
3
4use karyon_core::async_runtime::net::UdpSocket;
5
6use crate::{Endpoint, Result};
7
8#[derive(Default)]
10pub struct UdpConfig {}
11
12pub struct UdpConn {
14 socket: Arc<UdpSocket>,
15}
16
17impl UdpConn {
18 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 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 pub fn local_endpoint(&self) -> Result<Endpoint> {
32 Ok(Endpoint::new_udp_addr(self.socket.local_addr()?))
33 }
34
35 pub fn peer_endpoint(&self) -> Result<Endpoint> {
37 Ok(Endpoint::new_udp_addr(self.socket.peer_addr()?))
38 }
39}
40
41pub 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
51pub 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}