Tomcat에 비동기 서블릿을 구현하려고합니다. HttpSessionAttributeListener.attributeReplaced()
이 트리거 될 때마다 클라이언트에 업데이트를 보냅니다. 클라이언트 쪽에서 서버 보낸 이벤트를 받도록 구성됩니다.HttpServlet에서 AsyncContext로 응답이 없습니다.
수신기는 업데이트를 수신하지만 브라우저는 응답을받지 못합니다. 브라우저의 개발자 창에 요청이 pending
이고 AsyncContext.setTimeout()
으로 설정된 시간 초과 후 오류 500
으로 끝납니다. 나는 아이디어가 없어 졌는데, 왜 이런 일이 일어나고 있는지.
JS
var source = new EventSource('/acount/sse');
source.onmessage = function (event) {
console.log(event.data);
document.querySelector('#messageArea p').innerHTML += event.data;
};
그리고 이것은 내 서블릿 코드 :
서블릿
public class SSE extends HttpServlet implements HttpSessionAttributeListener {
public static final String ATTR_ENTRY_PROCESSOR_PROGRESS = "entryProcessorProgress";
private AsyncContext aCtx;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", true);
resp.setContentType("text/event-stream");
resp.setHeader("Cache-Control", "no-cache");
resp.setHeader("Connection", "keep-alive");
resp.setCharacterEncoding("UTF-8");
aCtx = req.startAsync(req, resp);
aCtx.setTimeout(80000);
}
@Override
public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
write(httpSessionBindingEvent);
}
@Override
public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {
}
@Override
public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {
write(httpSessionBindingEvent);
}
private void write(HttpSessionBindingEvent httpSessionBindingEvent) {
if (httpSessionBindingEvent.getName().equals(ATTR_ENTRY_PROCESSOR_PROGRESS)) {
try {
String message = "data: " + httpSessionBindingEvent.getValue() + "\n\n";
aCtx.getResponse().getWriter().write(message);
aCtx.getResponse().getWriter().flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
감사합니다. –