4
我有一個使用servlet簡單的服務器發送事件的運行實現。服務器使用服務器端發送事件作爲servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
try
{
System.out.println("Server Sent Events");
response.setContentType("text/event-stream");
PrintWriter pw = response.getWriter();
int i=0;
pw.write("retry: 30000\n");
System.out.println("----------------------");
while(true)
{
i++;
pw.write("data: "+ i + "\n\n");
System.out.println("Data Sent : "+i);
if(i>10)
break;
}
}catch(Exception e){
e.printStackTrace();
}
}
而我的客戶端代碼是
<!DOCTYPE html>
<html>
<body onload ="SSE()" >
<script>
function SSE()
{
var source = new EventSource('GetDate');
source.onmessage=function(event)
{
document.getElementById("result").innerHTML+=event.data + "<br />";
};
}
</script>
<output id ="result"></output>
</body>
</html>
但任何人都可以解釋我這實際上是如何工作的? 就像服務器如何一次發送11個整數塊? 是否需要在此處刷新或關閉Printwriter。 服務器是否每次都發起新的連接以發送數據
不完全是重複的,但[是一個很好的解釋](http://stackoverflow.com/q/5195452/575527) – Joseph 2013-05-07 06:38:51
有一個特殊的原因,你爲什麼使用'while'循環?你從0到10,這是'for'循環的共同目的...... – 2013-05-07 06:40:22
你究竟有什麼不明白,你已經明白了什麼?你試圖找出「它」是如何工作的?拋出一些代碼並說「請解釋」對我來說似乎不是一個好問題... – Uooo 2013-05-07 06:43:06