3

I have a TcpStream from which I need to read N bytes and send them as HttpResponse (I will still need to use the stream later on). At the moment I'm using the following code:

use futures::channel::mpsc;
use actix_web::HttpResponse;
use tokio::net::TcpStream;

let stream: TcpStream = ...;
let mut stream = stream.take(N);
let (mut sender, receiver) = mpsc::unbounded();

loop {
    let mut buffer = vec![0; BUFF_SIZE];
    let n = stream.read(&mut buffer).await?;
    if n > 0 {
        buffer.truncate(n);
        let data = Ok(web::Bytes::from(buffer));
        sender.send(data).await?;
    } else {
        break;
    }
}

// do more stuff with the TCP stream
let mut stream = stream.into_inner();
...


Ok(HttpResponse::Ok().streaming(receiver))

It works, but I'd like to know if it could be improved, as I couldn't find a better solution that wouldn't require the use of the mpsc::channel as well as the need to allocate a new buffer and web::Bytes for every read (besides the fact that I need to specify an arbitrary BUFF_SIZE).

Nick
  • 10,309
  • 21
  • 97
  • 201

0 Answers0