Skip to content

how can i use a channel in tokio::select! #3581

Answered by Darksonn
xiashaohua asked this question in Q&A
Discussion options

You must be logged in to vote

This is because you are blocking the thread by using a channel whose recv method does not involve an .await. You should be using tokio::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:

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(B…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@xiashaohua
Comment options

Answer selected by Darksonn
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants