我试图在此视频https://www.youtube.com/watch?v=rhCKCKD0KnA
中举例说明SSE response.setContentType("text/event-stream");
response.setCharacterEncoding("UTF-8");
PrintWriter printWriter = null;
while(true) {
try {
double rnd = Math.random() * 10000;
printWriter = response.getWriter();
printWriter.print("Rnd: " + rnd);
response.flushBuffer();
Thread.sleep(5000);
}
catch(IOException | InterruptedException e) {
e.printStackTrace();
printWriter.close();
break;
}
}
和客户方
window.onload = function () {
startButton.onclick = () => {
eventSource = new EventSource('http://localhost:8080/byteslounge-1/sse_test');
eventSource.onopen = () => {
displayTextArea.value += 'connected...' + '\n';
};
eventSource.onmessage = (message) => {
displayTextArea.value += message.data + '\n\n';
};
eventSource.onerror = () => {
displayTextArea.value += 'error occured...' + '\n';
};
startButton.disabled = true;
};
takeMsg.onclick = () => {
eventSource.onmessage = (message) => {
displayTextArea.value += message.data + '\n\n';
};
};
stopButton.onclick = () => {
eventSource.close();
startButton.disabled = false;
};
clearText.onclick = () => {
displayTextArea.value = '';
}
}
连接正常,但无法接收onMessage中的任何数据。服务器/客户端上没有错误/警告。我正在使用FF 64位最后版本/ JDK 1.8 / Payara。
答案 0 :(得分:0)
我的代码中没有看到任何明显的问题。但是,在使用Payara 5时,我建议使用JAX-RS SSE API而不是在servlet中自己编写代码。
请在此处查看示例和指南:http://ridingthecrest.com/blog/2017/02/22/jax-rs-2_1-new-feature-introduction.html
使用JAX-RS SSE的服务器端点的替代方案:
@Path("server-sent-events")
@Singleton
public class ServerSentEventsResource {
@GET
@Produces(MediaType.SERVER_SENT_EVENTS)
public void getMessageQueue(@Context SseEventSink eventSink, @Context Sse sse) {
while(true) {
try {
double rnd = Math.random() * 10000;
eventSink.send(sse.newEvent("custom-message"));
Thread.sleep(5000);
}
catch(IOException | InterruptedException e) {
e.printStackTrace();
printWriter.close();
break;
}
}
}
}
还使用通用SSE客户端测试服务器端点,例如curl支持SSE并打印传入的事件。如果可行,那么您的javascript客户端会出错。