提问人:Austin Hamner 提问时间:10/13/2022 最后编辑:HerohtarAustin Hamner 更新时间:10/15/2022 访问量:184
HTTP 响应流 - JavaScript 以 1 个大块或数据包的形式接收数据,而不是以碎片的形式接收数据
HTTP Response Streaming - JavaScript Receiving data as 1 big chunk or packet instead of in pieces
问:
我正在尝试从 Web 服务器流式传输 HTTP 响应,并从 JavaScript 端的流中读取每个数据块。JavaScript 端将所有数据作为 1 个块或数据包接收,而不是像我想要的那样分段接收。
- 下面是 Rust 代码:
use std::convert::Infallible;
use async_stream::stream;
use actix_web::{get, HttpResponse};
use actix_web::web::Bytes;
#[get("/stream")]
pub async fn stream() -> HttpResponse {
HttpResponse::Ok()
.streaming(stream! {
let mut count = 0;
while count < 10 {
yield Ok::<_, Infallible>(Bytes::from(count.to_string()));
count += 1;
}
})
}
- 下面是 Javascript 代码:
async function get_stream() {
const response = await fetch('/stream');
const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
while (true) {
let {value, done} = await reader.read();
if (done) break;
console.log('Received', value);
}
console.log('Response fully received');
}
这是我在控制台中收到的内容:
Received 0123456789
stream.js:69 Response fully received
这是我尝试在控制台中接收的结果:
Received 0
Received 1
Received 2
Received 3
Received 4
Received 5
Received 6
Received 7
Received 8
Received 9
stream.js:69 Response fully received
答: 暂无答案
评论