Server Sent Event not working in Google Chrome

2020-03-06 03:17发布

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;.

4条回答
We Are One
2楼-- · 2020-03-06 03:50

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();
查看更多
何必那么认真
3楼-- · 2020-03-06 04:05

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?

查看更多
唯我独甜
4楼-- · 2020-03-06 04:05

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.

查看更多
三岁会撩人
5楼-- · 2020-03-06 04:08

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

查看更多
登录 后发表回答