我有一个非常简单的 SSE(Html5 服务器发送事件),在服务器端使用 Java。我在下面包含了客户端和服务器。问题是,如果我更改服务器端,即使是简单的更改,例如更改调试输出中的文本,与发送到服务器的实际文本无关,客户端也会停止发布接收到的消息。根据在服务器端打印的输出消息,以及我在 Firebug 和 Chrome 的开发人员工具中看到的请求流量,我可以看到服务器正在发送消息,而浏览器接收到消息。唯一的问题是接收到 SSE 时应该触发的 JavaScript 函数没有被触发。有什么建议,或者你觉得我的代码有什么问题吗?
<!DOCTYPE html>
<html>
<body>
<h1>Getting server updates</h1>
<div id="result"></div>
<script>
if(typeof(EventSource)!=="undefined")
{
var source=new EventSource("/ServerSideForSSE/sse3");
source.onmessage=function(event)
{
document.getElementById("result").innerHTML+=event.data + "<br>";
};
}
else
{
document.getElementById("result").innerHTML=
"Sorry, your browser does not support server-sent events...";
}
</script>
</body>
</html>
package com.ultratech;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/sse3")
public class sse3 extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
response.setCharacterEncoding("utf-8");
response.setContentType("text/event-stream");
PrintWriter out = response.getWriter();
int x = 0;
while (x < 100)
{
x++;
Date currentTime_1 = new Date();
out.println("Current Time is: " + currentTime_1);
out.println();
out.flush();
System.out.println("Another message sent to the cleint ...");
if (x > 100) {System.exit(0);}
try {
Thread.sleep(5 * 1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}//End of for().
out.close();
}//End of doGet().
}