utils_box_connections/
udp_client.rs1use anyhow::{Result, bail};
6use std::net::UdpSocket;
7
8use utils_box_logger::{log_error, log_info, log_trace};
9
10pub static BUFFER_SIZE: usize = 500;
11
12pub struct UdpClient {
13 server_ip: String,
14 server_port: u16,
15 udp_socket: UdpSocket,
16}
17
18impl UdpClient {
19 pub fn new(local_ip: String, server_ip: String, server_port: u16) -> Result<Self> {
20 let udp_socket = UdpSocket::bind(format!("{local_ip}:{server_port}"))?;
21
22 Ok(UdpClient {
23 server_ip,
24 server_port,
25 udp_socket,
26 })
27 }
28
29 pub fn connection_info(&self) -> (String, u16) {
30 (self.server_ip.clone(), self.server_port)
31 }
32
33 pub fn send(&mut self, data: &[u8]) -> Result<()> {
34 match self
35 .udp_socket
36 .send_to(data, format!("{}:{}", self.server_ip, self.server_port))
37 {
38 Ok(_) => {
39 log_trace!(
40 "[UdpClient][{}:{}] Send [{} Bytes] to [{}] SUCCESSFULLY!",
41 self.server_ip,
42 self.server_port,
43 data.len(),
44 self.server_ip,
45 );
46 Ok(())
47 }
48 Err(e) => {
49 log_error!(
50 "[UdpClient][{}:{}] Send FAILED with [{}]",
51 self.server_ip,
52 self.server_port,
53 e
54 );
55 bail!(e)
56 }
57 }
58 }
59
60 pub fn receive(&mut self) -> Result<Vec<u8>> {
61 let mut data: Vec<u8> = vec![0; BUFFER_SIZE];
62
63 match self.udp_socket.recv_from(&mut data) {
64 Ok((data_len, src_addr)) => {
65 log_trace!(
66 "[UdpClient][{}:{}] Received [{} Bytes] from [{}] SUCCESSFULLY!",
67 self.server_ip,
68 self.server_port,
69 data_len,
70 src_addr,
71 );
72 Ok(data[..data_len].to_vec())
73 }
74 Err(e) => {
75 log_error!(
76 "[UdpClient][{}:{}] Receive FAILED with [{}]",
77 self.server_ip,
78 self.server_port,
79 e
80 );
81 bail!(e)
82 }
83 }
84 }
85}
86
87impl Drop for UdpClient {
88 fn drop(&mut self) {
89 log_info!(
90 "[UdpClient] Disconnected from [{}:{}]",
91 self.server_ip,
92 self.server_port
93 );
94 }
95}