-
I'm using Tokio to handle udp connections in a tauri app, interfacing with the frontend via an event system. I need the frontend to be able to close the udp connection, but it's unclear how to do this. I've tried a few different methods, e.g. that outlined here, but all have some sort of error. In the case of the linked solution, I was receiving errors that the channel could not be implicitly typed due to being in an async function. I've also tried using something like Here is my current code, with no attempted solution, as all of my attempts so far have been much harder to read. #[tauri::command]
async fn start_udp_server(app_handle: tauri::AppHandle, address: String) -> Result<(), String> {
match UdpSocket::bind(address.to_string()).await {
Ok(socket) => {
let framed = UdpFramed::new(socket, BytesCodec::new());
let (_write, read) = framed.split();
let udp_listener = {
read.for_each(|udp_message| async {
match udp_message {
Ok((bytes, _socket_address)) => {
app_handle.emit_all("udp_trigger", bytes.to_ascii_lowercase()).unwrap();
},
Err(error) => {
println!("udp error: {}", error);
}
}
})
};
app_handle.listen_global("udp_close", |_| {
println!("got close command");
// how to close?
});
app_handle.emit_all("udp_listening", true).unwrap();
udp_listener.await;
println!("closed");
Ok(())
},
Err(_) => Err("Error binding to address".into())
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
Give this a try: let (send, mut recv) = tokio::sync::mpsc::channel::<()>();
app_handle.listen_global("udp_close", move |_| {
println!("got close command");
send.send(());
});
app_handle.emit_all("udp_listening", true).unwrap();
tokio::select! {
_ = udp_listener => {},
_ = recv.recv() => {},
}
println!("closed");
Ok(()) |
Beta Was this translation helpful? Give feedback.
Give this a try: