aboutsummaryrefslogtreecommitdiff
path: root/src/transport/udp.rs
blob: c0d78290c26d83e26918b4fb18b0ef2a2ad09fb2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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(())
    }
}