From 091bcf33da7a1bb3eea466dda9dbf3a3488df710 Mon Sep 17 00:00:00 2001 From: Ivan Li Date: Sat, 6 May 2023 20:14:31 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=94=AF=E6=8C=81=E6=94=B6=E5=8F=96?= =?UTF-8?q?=E6=9D=A5=E8=87=AA=E6=9D=BF=E5=AD=90=E8=A6=81=E6=B1=82=E7=9A=84?= =?UTF-8?q?=E6=98=BE=E7=A4=BA=E5=99=A8=E4=BA=AE=E5=BA=A6=E5=92=8C=E7=94=B5?= =?UTF-8?q?=E8=84=91=E9=9F=B3=E9=87=8F=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src-tauri/src/rpc/board.rs | 60 +++++++++++++++++++++++++++++++------- 1 file changed, 49 insertions(+), 11 deletions(-) diff --git a/src-tauri/src/rpc/board.rs b/src-tauri/src/rpc/board.rs index c64bf1c..c8cbbce 100644 --- a/src-tauri/src/rpc/board.rs +++ b/src-tauri/src/rpc/board.rs @@ -1,21 +1,23 @@ -use std::time::Duration; +use std::{sync::Arc, time::Duration}; -use paris::{info, warn}; -use tokio::{net::UdpSocket, sync::RwLock, time::timeout}; +use paris::{info, warn, error}; +use tokio::{net::UdpSocket, sync::RwLock, time::timeout, io}; use super::{BoardConnectStatus, BoardInfo}; #[derive(Debug)] pub struct Board { - pub info: RwLock, - socket: Option, + pub info: Arc>, + socket: Option>, + listen_handler: Option>, } impl Board { pub fn new(info: BoardInfo) -> Self { Self { - info: RwLock::new(info), + info: Arc::new(RwLock::new(info)), socket: None, + listen_handler: None, } } @@ -24,7 +26,33 @@ impl Board { let socket = UdpSocket::bind("0.0.0.0:0").await?; socket.connect((info.address, info.port)).await?; - self.socket = Some(socket); + let socket = Arc::new(socket); + self.socket = Some(socket.clone()); + + let info = self.info.clone(); + + let handler=tokio::spawn(async move { + let mut buf = [0u8; 128]; + if let Err(err) = socket.readable().await { + error!("socket read error: {:?}", err); + return; + } + loop { + match socket.try_recv(&mut buf) { + Ok(len) => { + log::info!("recv: {:?}", &buf[..len]); + } + Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => { + continue; + } + Err(e) => { + error!("socket recv error: {:?}", e); + break; + } + } + } + }); + self.listen_handler = Some(handler); Ok(()) } @@ -37,10 +65,7 @@ impl Board { let socket = self.socket.as_ref().unwrap(); - socket - .send(buf) - .await - .unwrap(); + socket.send(buf).await.unwrap(); } pub async fn check(&self) -> anyhow::Result<()> { @@ -99,3 +124,16 @@ impl Board { Ok(()) } } + + +impl Drop for Board { + fn drop(&mut self) { + if let Some(handler) = self.listen_handler.take() { + info!("aborting listen handler"); + tokio::task::block_in_place(move || { + handler.abort(); + }); + info!("listen handler aborted"); + } + } +} \ No newline at end of file