Dart Chucked HTTP服务器响应
我正在开发一个简单的DART HTTP服务器,该服务器必须返回流的值作为HTTP响应。我想在块中发送流的数据,有人知道如何在DART中做到这一点吗?我之前已经创建了一次应用程序,这就是代码的样子:
...
func(w http.ResponseWriter, r *http.Request){
flusher, ok := w.(http.Flusher)
w.Header().Set("Connection", "Keep-Alive")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Transfer-Encoding", "chunked")
w.Header().Set("Content-Type", "audio/mpeg")
for (...) {
w.Write(b)
flusher.Flush()
}
...
}
...
这就是我到目前为止的DART,但是齐平功能无法正常工作:
final server = await HttpServer.bind(InternetAddress.anyIPv4, 8080);
await for (var request in server) {
final stream = await _audio.stream();
final response = request.response;
StreamSubscription? subscription;
response.done.then((value) => subscription?.cancel());
request.response
..headers.contentType = ContentType("audio", "mpeg")
..headers.add("Connection", "Keep-Alive")
..headers.add("Access-Control-Allow-Origin", "*")
..headers.add("X-Content-Type-Options", "nosniff")
..headers.add("Transfer-Encoding", "chunked");
subscription = stream?.listen((event) {
response.write(event);
response.flush(); // Here
});
}
齐平方法在调用时会引发错误,即”不良状态:StreamSink绑定到流。
I'm developing a simple Dart HTTP server which must return the values of a stream as HTTP response. I want to send the data of the streams in chunks, does someone know how to do this in Dart? I have created the application once before in Go, this is how the code looked like:
...
func(w http.ResponseWriter, r *http.Request){
flusher, ok := w.(http.Flusher)
w.Header().Set("Connection", "Keep-Alive")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Transfer-Encoding", "chunked")
w.Header().Set("Content-Type", "audio/mpeg")
for (...) {
w.Write(b)
flusher.Flush()
}
...
}
...
This is what I have so far in Dart, but the flush function does not work as I expected:
final server = await HttpServer.bind(InternetAddress.anyIPv4, 8080);
await for (var request in server) {
final stream = await _audio.stream();
final response = request.response;
StreamSubscription? subscription;
response.done.then((value) => subscription?.cancel());
request.response
..headers.contentType = ContentType("audio", "mpeg")
..headers.add("Connection", "Keep-Alive")
..headers.add("Access-Control-Allow-Origin", "*")
..headers.add("X-Content-Type-Options", "nosniff")
..headers.add("Transfer-Encoding", "chunked");
subscription = stream?.listen((event) {
response.write(event);
response.flush(); // Here
});
}
The flush method throws an error when called, namely "Bad state: StreamSink is bound to a stream".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在
架子
中,您可以使用这样的处理程序当然可以在没有缓冲区的情况下流式传输:In
shelf
you can certainly stream without buffer, using a handler like this: