-
My problem is when a TCP connection is established, I can get a frame from the connection and do some job. But the job could be time-consuming and when the job is finished, some response is needed to be written back to the connection.
if |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 7 replies
-
There are several options, but here is one: async fn process(stream: TcpStream, pet: Arc<Mutex<State>>) -> Result<(), Box<dyn Error>> {
let (write, read) = Framed::new(stream, PetCodec).split(); // futures::stream::StreamExt
let (send, recv) = tokio::sync::mpsc::channel(16);
tokio::try_join!(
async move {
while let Some(frm) = read.next().await {
match frm {
Ok(frm) => {
let send = send.clone();
let pet = pet.clone();
tokio::spawn(async move {
let response = handle_request(frm, pet).await;
let _ = send.send(response).await;
});
}
Err(e) => return Err(e.into()),
}
}
drop(send);
// this type annotation is necessary to help out the compiler
Result::<(), Box<dyn Error>>::Ok(())
},
async move {
while let Some(response) = recv.recv().await {
write.send(response)?;
}
Ok(())
}
)?;
Ok(())
} |
Beta Was this translation helpful? Give feedback.
There are several options, but here is one: