我正在尝试使用OutboundSseEvent类在Java服务器中设置服务器发送的事件。我不确定为什么我的代码会不断抛出空指针异常。我正在使用这些教程作为参考。 https://www.baeldung.com/java-ee-jax-rs-sse和https://www.programcreek.com/java-api-examples/index.php?api=javax.ws.rs.sse.OutboundSseEvent
@Path("ssetest")
public class SSETestService extends SecureService {
private Sse sse;
@GET
@Path("/test")
@Produces("text/event-stream")
public void SSETestService(@Context Sse sse,SseEventSink sseEventSink)
throws InterruptedException,IllegalArgumentException {
OutboundSseEvent stringEvent = sse.newEventBuilder()
.name("ping")
.data("hello world").build();
sseEventSink.send(stringEvent);
}
}
在客户端...
testSSE() {
console.log("in testSSE()");
const evtsource = new Eventsource(
"http://localhost:8081/api/ssetest/test"
);
evtsource.onmessage = function(event) {
console.log("received message");
console.log("event.data: " + event.data);
};
evtsource.addEventListener("ping",function(event) {
console.log("event.data: " + event.data);
console.log("received ping event");
});
evtsource.onerror = function(err) {
console.error("Eventsource failed:",err);
};
}
感谢任何指针。