简体   繁体   English

如何使用 TcpStream 拆分为 2 个异步线程?

[英]How do I use TcpStream split across 2 threads with async?

I am trying to use the read and write of a tcp stream in different threads.我正在尝试在不同的线程中使用 tcp stream 的读写。 This is what I currently have:这是我目前拥有的:

use tokio::prelude::*;
use tokio::net::TcpStream;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut stream = TcpStream::connect("localhost:8080").await?;
    let (mut read, mut write) = stream.split();

    tokio::spawn(async move {
        loop {
            let mut buf = [0u8; 32];
            read.read(&mut buf).await.unwrap();
            println!("{}", std::str::from_utf8(&buf));
        }
    });

    Ok(())
}

Im going to use another thread for the write.我将使用另一个线程进行写入。 My problem is that I get the error that 'stream' is dropped while still borrowed.我的问题是我得到了“流”在仍然借用时被丢弃的错误。

That happens due to the method signature of Tokio::split , as you can see it takes &mut self , so its part cannot be used in a tokio::spawn future argument due to the 'static bound.这是由于Tokio::split的方法签名而发生的,您可以看到它需要&mut self ,因此由于'static绑定”,它的部分不能在tokio::spawn未来参数中使用。 So, this is exactly what the error says.所以,这正是错误所说的。

What you are searching is tokio::io::split .您正在搜索的是tokio::io::split Playground 操场

use tokio::prelude::*;
use tokio::net::TcpStream;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut stream = TcpStream::connect("localhost:8080").await?;
    let (mut read, mut write) = tokio::io::split(stream);

    tokio::spawn(async move {
        loop {
            let mut buf = [0u8; 32];
            read.read(&mut buf).await.unwrap();
            println!("{:?}", std::str::from_utf8(&buf));
        }
    });

    Ok(())
}

Reading https://users.rust-lang.org/t/why-i-have-to-use-tokio-tcpstream-split-for-concurrent-read-writes/47755/3 And it suggests to use into_split it is more efficient.阅读https://users.rust-lang.org/t/why-i-have-to-use-tokio-tcpstream-split-for-concurrent-read-writes/47755/3它建议使用into_split它是更高效。

tokio::io::split uses a Mutex which into_split apparently does not have (specific to TcpStream ) tokio::io::split使用了into_split显然没有的Mutex (特定于TcpStream

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM