Server Sent Event not working in Google Chrome

2020-03-06 03:14发布

问题:

This is my server JSP code "Server_Date.jsp"

<%
response.setHeader("cache-control", "no-cache"); 
response.setContentType("text/event-stream");
out.print("data: " + (new java.util.Date()).toString() + "x\n\n");
out.flush();   
%>

This my client jsp page "Client_Serverdate.jsp"

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"     "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body  onload="begin()">
<h1>Getting server updates</h1>
<div id="result"></div>
<script >
if(typeof(EventSource)!=="undefined")
{     
var source=new EventSource("Server_Date.jsp");      
source.addEventListener("message", function(event) {
    document.getElementById("result").innerHTML = event.data;
}, false);
}
else
{
document.getElementById("result").innerHTML="Sorry, your browser does not support server-sent events...";
}
</script>   
</body>
</html>

Please help me this code is working fine in Mozilla Firefox, Opera but not working in Google Chrome (I was checked with 18.x and 20.x also).

It is going to server page I have checked with print statement but its not coming to the line document.getElementById("result").innerHTML = event.data;.

回答1:

For one you are calling a function begin() that is not defined although that should not be the issue here.

Does the Chrome development console show any errors? It should show at least one. because of the begin function. And does the network tab show traffic to Server_Date.jsp?



回答2:

I used to have the same issue. As server part, I used PHP, but I guess it works the same. What fixed it for me was adding ob_flush(). Now, I don't know what it should be in your language, but maybe it helps you in the right direction.



回答3:

I've met the same problem, and i resolved it by add a newline at the end of the servlet. like this:

response.setContentType("text/event-stream;charset=UTF-8");
response.addHeader("Cache-Control", "no-cache");
PrintWriter out = response.getWriter();
out.println("data: " + new Date());
out.println();
out.flush();
out.close();


回答4:

Problem was solved

Solution :

Page encoding problem : client side used UTF-8 Encoding

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

Server side UTF-8 was not mention, so after adding charset=UTF-8 in setContentType its working

response.setContentType("text/event-stream;charset=UTF-8");

Thanks for people take your effort to answer my question