2014-04-15 28 views
1

我想從頭開始設計一個系統,我想通過servlet加載文本行。生產線需要一些時間。因此,我希望能夠在他們到達時逐步在瀏覽器中顯示它們,一次一個。我想從JavaScript發送一個請求到我的servlet。Servlet/Javascript chunking

我一直在研究這個,我找不到解決方案。在我的servlet中,我需要做什麼才能一次刷新幾行?我需要做什麼在我的JavaScript檢索這些刷新的行直到流的結束?是否有可能,還是需要將多個請求分頁到我的servlet?

感謝

回答

2

在服務器端,您可以使用要求的Reader,並且響應的WriterflushBuffer方法的組合的組合。

這個想法是從輸入流中讀取一大塊數據,例如,使用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 readyState3(處理請求):

<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> 
+1

明白了。怎麼樣的JavaScript?我如何獲得偏好? –

+1

已更新,其中包含一個JavaScript示例。 – earldouglas

+1

我把一個完整的例子(演示)[在這裏](https://github.com/earldouglas/xwp-template/tree/chunky#chunked-http-with-ajax-and-scala)放在一起。 – earldouglas

相關問題