how can i use a channel in tokio::select! #3581
-
I'm learning about Rust, and I tried to use a the code is:
receive_write_data is:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
This is because you are blocking the thread by using a channel whose You can receive on it like this: use tokio::sync::mpsc;
let mut transport = Framed::new(stream, BytesCodec::new());
let (message_sender, message_receiver) = mpsc::channel();
loop {
println!("into loop");
tokio::select! {
Some(data) = transport.next() => {
...
},
Some(res) = message_receiver.recv() => {
let response = create_message_by_struct(v);
transport.send(Bytes::copy_from_slice(&response.as_bytes())).await?;
},
else => {
println!("channel and connection both closed");
break;
}
}
} Additionally, please note that it pretty much never makes sense to put a channel receiver into a |
Beta Was this translation helpful? Give feedback.
This is because you are blocking the thread by using a channel whose
recv
method does not involve an.await
. You should be usingtokio::sync::mpsc
instead, which is a channel designed for async code. For more info, see the channels chapter in the Tokio tutorial.You can receive on it like this: