actix_web 1.0:逐步发送分块响应

时间:2019-07-14 04:40:19

标签: rust-actix actix-web

我正在尝试通过HTTP 1.1 HTTP分块响应来实现twitter-alike streaming API

用例:http客户端与我的服务器建立了连接,HTTP连接保持活动状态,并且永远不会主动关闭服务器。当有任何事件通知客户端时,我的服务器会在活动连接上发出一个HTTP块。

enter image description here

问题:如何在actix_web 1.0中逐步发送分块响应?

extern crate actix_web;
use actix_web::{
    error, guard, middleware, web, App, Error, HttpRequest, HttpResponse, HttpServer, Responder,
    Result,
};

use bytes::Bytes;
use futures::stream::Stream;
use futures::sync::mpsc;
use std::{thread, time};


/// async body
fn index_async_body() -> HttpResponse {
    let text = "Something!";

    let (tx, rx_body) = mpsc::unbounded();

    thread::spawn(move || loop {
        let _ = tx.unbounded_send(Bytes::from(text.as_bytes()));
        let ten_millis = time::Duration::from_millis(100);
        thread::sleep(ten_millis);
    });

    HttpResponse::Ok().streaming(rx_body.map_err(|_| error::ErrorBadRequest("bad request")))
}

pub fn run() {
    HttpServer::new(|| App::new().route("/", web::get().to(index_async_body)))
        .bind("127.0.0.1:8088")
        .unwrap()
        .run()
        .unwrap();
}

上面的代码无法逐步发出块。看来它已经被缓冲了。

0 个答案:

没有答案