如何将 TcpStream 拆分为异步的 2 个线程?

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

我正在尝试在不同线程中使用TCP 流的读写。这是我目前拥有的:

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(())
}

我将使用另一个线程进行写入。我的问题是我得到的错误是 'stream' 在借用时被丢弃。

这是由于 Tokio::split 的方法签名而发生的,如您所见,它需要 &mut self,因此由于 'static绑定。所以,这正是错误所说的。

您搜索的是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(())
}