webrtc_util/conn/
conn_disconnected_packet.rs

1use std::net::Ipv4Addr;
2use std::sync::Arc;
3
4use super::*;
5use crate::sync::RwLock;
6
7/// Since UDP is connectionless, as a server, it doesn't know how to reply
8/// simply using the `Write` method. So, to make it work, `disconnectedPacketConn`
9/// will infer the last packet that it reads as the reply address for `Write`
10pub struct DisconnectedPacketConn {
11    raddr: RwLock<SocketAddr>,
12    pconn: Arc<dyn Conn + Send + Sync>,
13}
14
15impl DisconnectedPacketConn {
16    pub fn new(conn: Arc<dyn Conn + Send + Sync>) -> Self {
17        DisconnectedPacketConn {
18            raddr: RwLock::new(SocketAddr::new(Ipv4Addr::new(0, 0, 0, 0).into(), 0)),
19            pconn: conn,
20        }
21    }
22}
23
24#[async_trait]
25impl Conn for DisconnectedPacketConn {
26    async fn connect(&self, addr: SocketAddr) -> Result<()> {
27        self.pconn.connect(addr).await
28    }
29
30    async fn recv(&self, buf: &mut [u8]) -> Result<usize> {
31        let (n, addr) = self.pconn.recv_from(buf).await?;
32        *self.raddr.write() = addr;
33        Ok(n)
34    }
35
36    async fn recv_from(&self, buf: &mut [u8]) -> Result<(usize, SocketAddr)> {
37        self.pconn.recv_from(buf).await
38    }
39
40    async fn send(&self, buf: &[u8]) -> Result<usize> {
41        let addr = *self.raddr.read();
42        self.pconn.send_to(buf, addr).await
43    }
44
45    async fn send_to(&self, buf: &[u8], target: SocketAddr) -> Result<usize> {
46        self.pconn.send_to(buf, target).await
47    }
48
49    fn local_addr(&self) -> Result<SocketAddr> {
50        self.pconn.local_addr()
51    }
52
53    fn remote_addr(&self) -> Option<SocketAddr> {
54        let raddr = *self.raddr.read();
55        Some(raddr)
56    }
57
58    async fn close(&self) -> Result<()> {
59        self.pconn.close().await
60    }
61
62    fn as_any(&self) -> &(dyn std::any::Any + Send + Sync) {
63        self
64    }
65}