我正在开发一个简单的Dart HTTP服务器,它必须返回流的值作为HTTP响应。我想发送数据流的数据块,有人知道如何在Dart中实现这个吗?我曾经在Go中创建过一次应用程序,这是代码的样子:
...
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中的内容,但是flush函数不像我预期的那样工作:
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
});
}
调用flush方法时会抛出错误,即"状态不良:StreamSink绑定到流"。
在shelf
你当然可以流没有缓冲区,使用这样的处理程序:
Future<Response> audioHandler(Request request) async {
final stream = [await] getTheStream();
return Response.ok(
stream,
headers: {
'Cache-Control': 'no-store',
'Content-Type': 'audio/whatever',
// any other response headers
},
context: {
'shelf.io.buffer_output': false,
},
);
}