diff options
Diffstat (limited to 'sip/src/transport/udp.rs')
-rw-r--r-- | sip/src/transport/udp.rs | 35 |
1 files changed, 35 insertions, 0 deletions
diff --git a/sip/src/transport/udp.rs b/sip/src/transport/udp.rs new file mode 100644 index 0000000..c0d7829 --- /dev/null +++ b/sip/src/transport/udp.rs @@ -0,0 +1,35 @@ +use super::Transport; +use crate::encoding::Message; +use anyhow::{anyhow, Result}; +use log::debug; +use std::str::FromStr; +use tokio::net::UdpSocket; + +pub struct UdpTransport { + sock: UdpSocket, +} + +impl UdpTransport { + pub async fn new(sock: UdpSocket) -> Result<Self> { + Ok(Self { sock }) + } +} +impl Transport for UdpTransport { + async fn recv(&self) -> Result<Message> { + let mut buf = [0; 1024]; + let size = self.sock.recv(&mut buf).await?; + let message = String::from_utf8(buf[..size].to_vec())?; + let (head, body) = message + .split_once("\r\n\r\n") + .ok_or(anyhow!("header end missing"))?; + debug!("<- {head}\n\n{body}"); + let mut mesg = Message::from_str(head.trim_end())?; + *mesg.body_mut() = body.to_string(); + Ok(mesg) + } + async fn send(&self, request: Message) -> Result<()> { + debug!("-> {request}"); + self.sock.send(format!("{request}").as_bytes()).await?; + Ok(()) + } +} |