JS EventSource从我的3.0异步servlet接收神秘错误

时间:2015-02-28 15:28:41

标签: java javascript server-sent-events

我的EventSource连接,输出被打印,但是当我调用asyncContext.complete()时,我的JS EventSource收到错误。 EventSource的错误永远不会显示消息。

对于那些投票结束的人:如果你下次提供理由,那就太好了。 我甚至发布了Git项目的链接。还应该做​​些什么呢? o.O

使用Tomcat 7.0.30,7.0.59,8.0.20进行测试

响应返回http状态OK / 200以及标题:

  • 连接:关闭
  • Content-Type:text / event-stream; charset = UTF-8
  • 日期:星期六,2015年2月28日21:32:35 GMT
  • 服务器:Apache-Coyote / 1.1
  • 转移编码:身份

如果有人愿意在这里尝试最小化的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" />

0 个答案:

没有答案