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

2

6

I am trying to use the read and write of a tcp stream in different threads. 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.

Acaroid answered 5/6, 2020 at 16:32 Comment(1)
How did you end up using the write in a different thread? Trying to get this work - or potentially return the whole connection so I can get it later - not working out the way I hoped haha. Any tips?Whale
W
7

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. So, this is exactly what the error says.

What you are searching is 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(())
}
Wilton answered 5/6, 2020 at 16:41 Comment(0)
D
0

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.

tokio::io::split uses a Mutex which into_split apparently does not have (specific to TcpStream)

Detergency answered 23/8, 2022 at 15:49 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.