在服務器端,您可以使用要求的Reader
,並且響應的Writer
和flushBuffer
方法的組合的組合。
這個想法是從輸入流中讀取一大塊數據,例如,使用getLine
,然後在服務器上以某種方式處理該行,然後使用getWriter.write
後跟flushBuffer
將一些信息寫入響應。
例如:
override def service(req: HttpServletRequest, res: HttpServletResponse) {
val r = req.getReader
def echoLines: Unit =
Option(r.readLine) foreach { line => // read a chunk from the request
// simulate slow server-side processing
Thread.sleep(1000)
// write a chunk to the response
res.getWriter.write("read line: " + line + "\n")
// force the response buffer to be written to the client
res.flushBuffer
// repeat until the request is completely processed
echoLines
}
echoLines
}
你可以捲曲進行測試(請務必使用-N
選項):
curl -N -X POST --data-binary @test.txt localhost:8080
在客戶端,你可以有你的代碼的反應時, XHR readyState
是3
(處理請求):
<html>
<head>
<script>
function go() {
var xhr;
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari
xhr = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
xhr.onreadystatechange=function() {
if (xhr.readyState == 3 && xhr.status == 200) {
var out = document.getElementById('out');
out.innerHTML = xhr.responseText;
}
}
xhr.open('POST', '/echo', true);
xhr.send('hello\nworld\n\n1\n2\n3\n4\n5');
}
</script>
</head>
<body onload="go()">
<pre id="out"></pre>
</body>
</head>
明白了。怎麼樣的JavaScript?我如何獲得偏好? –
已更新,其中包含一個JavaScript示例。 – earldouglas
我把一個完整的例子(演示)[在這裏](https://github.com/earldouglas/xwp-template/tree/chunky#chunked-http-with-ajax-and-scala)放在一起。 – earldouglas