从 Mochiweb 流式传输结果
我使用 Erlang 和 Mochiweb 编写了一个 Web 服务。 Web 服务返回大量结果,需要一些时间才能完成计算。 我想在程序找到结果后立即返回结果,而不是在找到全部结果后才返回结果。
编辑:
我发现我可以使用分块请求来流结果,但似乎我找不到关闭连接的方法。那么关于如何关闭 mochiweb 请求有什么想法吗?
I have written a web-service using Erlang and Mochiweb. The web service returns a lot of results and takes some time to finish the computation.
I'd like to return results as soon as the program finds it, instead of returning them when it found them all.
edit:
i found that i can use a chunked request to stream result, but seems that i can't find a way to close the connection. so any idea on how to close a mochiweb request?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要使用 HTTP 1.1 传输未知大小的数据,您可以使用 HTPP 分块传输编码。在此编码中,每个数据块都以其十六进制大小为前缀。最后一个块是一个零长度块,块大小编码为0,但没有任何数据。
如果客户端不支持 HTTP 1.1,服务器可以将数据作为二进制块发送,并在流末尾关闭连接。
在 MochiWeb 中,其工作原理如下:
Response = Request:响应({Code, ResponseHeaders, chunked}) 功能。 (顺便看一下代码注释);
Response:
To stream data of yet unknown size with HTTP 1.1 you can use HTPP chunked transfer encoding. In this encoding each chunk of data prepended by its size in hexadecimal. Last chunk is a zero-length chunk, with the chunk size coded as 0, but without any data.
If client doesn't support HTTP 1.1 server can send data as binary chunks and close connection at the end of the stream.
In MochiWeb it's all works as following:
Response = Request:
respond({Code, ResponseHeaders, chunked}) function. (By the way, look at the code comments);Response:
write_chunk(Data) function. To indicate client the end of the stream chunk of zero length should be sent:Response:write_chunk(<<>>)
.