我的EventSource连接,输出被打印,但是当我调用asyncContext.complete()时,我的JS EventSource收到错误。 EventSource的错误永远不会显示消息。
对于那些投票结束的人:如果你下次提供理由,那就太好了。 我甚至发布了Git项目的链接。还应该做些什么呢? o.O
使用Tomcat 7.0.30,7.0.59,8.0.20进行测试
响应返回http状态OK / 200以及标题:
如果有人愿意在这里尝试最小化的Maven项目:BitBucket.org
我尝试过关闭防病毒软件。
你能在这里看到任何可疑的东西吗?
JS:
function setupEventSource() {
var es = new EventSource('/sse');
es.onerror = function(event) {
console.log('[EventSource] Error while connecting to ' + es.url);
// es.close();
};
}
setupEventSource();
爪哇:
@WebServlet(urlPatterns = { "/sse" }, asyncSupported = true)
public class EventSource2 extends HttpServlet {
private static ScheduledExecutorService executor = Executors
.newScheduledThreadPool(10);
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/event-stream");
response.setCharacterEncoding("UTF-8");
final AsyncContext asyncContext = request.startAsync();
Runnable runnableDummy = new Runnable() {
@Override
public void run() {
try {
PrintWriter writer = asyncContext.getResponse().getWriter();
for (int i = 0; i < 5; i++) {
Thread.sleep(1000);
writer.println("data: Hello " + i + "\n");
writer.flush();
}
} catch (IOException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (InterruptedException e) {
throw new RuntimeException(e.getMessage(), e);
}
asyncContext.complete();
}
};
executor.execute(runnableDummy);
}
@Override
public void destroy() {
executor.shutdown();
}
}
server.xml中
<Connector port="80" protocol="HTTP/1.1"
URIEncoding="UTF-8" connectionTimeout="20000" asyncTimeout="20000" />