I am trying to use the read and write of a websocket in different threads. #282
-
https://github.com/tokio-rs/axum/blob/main/examples/websockets/src/main.rs use std::sync::Arc;
use tokio::sync::Mutex;
async fn handle_socket(mut socket: WebSocket) {
let socket=Arc::new(Mutex::new(socket));
tokio::spawn(async move {
loop {
if let Some(msg) = socket.lock().recv().await {
if let Ok(msg) = msg {
println!("Client says: {:?}", msg);
} else {
println!("client disconnected");
return;
}
}
}
});
loop {
if socket
.lock()
.send(Message::Text(String::from("Hi!")))
.await
.is_err()
{
println!("client disconnected");
return;
}
tokio::time::sleep(std::time::Duration::from_secs(3)).await;
}
} |
Beta Was this translation helpful? Give feedback.
Answered by
davidpdrsn
Aug 28, 2021
Replies: 1 comment 4 replies
-
Since WebSocket implements Stream and Sink you can use split to get a read and write half. Those can be moved to different threads. It's also shown here https://github.com/tokio-rs/axum/blob/main/examples/chat/src/main.rs |
Beta Was this translation helpful? Give feedback.
4 replies
Answer selected by
davidpdrsn
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Since WebSocket implements Stream and Sink you can use split to get a read and write half. Those can be moved to different threads.
It's also shown here https://github.com/tokio-rs/axum/blob/main/examples/chat/src/main.rs