I have set up SSE (server-sent-events) in a Java server. The client is built on VueJS and uses the EventSource package to receive events from the server. I am using the EventSourcePolyfill npm package https://www.npmjs.com/package/event-source-polyfill on the client. This package allows us to send an authorization header (for our security scheme) with the request.
The client sends a request to our SSE service and receives a single event of type "open". The SSE then sends no further events or does send events and the browser does not detect them. Why is this? Suggestions for fixing? There are no error messages.
This behavior occurs in Chrome, Firefox and Edge, so it probably has nothing to do with the browser.
Our client method...
testSSE() {
console.log("in testSSE()");
console.log("apikey: " + store.user.apikey);
var EventSource = EventSourcePolyfill;
const evtSource = new EventSource(
"http://localhost:8081/api/ssetest/test",
{ headers: { Authorization: "Bearer " + store.user.apikey } }
);
evtSource.onmessage = function(event) {
console.log("received message");
console.log("event.data: " + event.data);
};
//This is the only function that gets hit
evtSource.addEventListener("open", function(event) {
console.log("open event");
console.log(Object.keys(event));
console.log(event.type);
});
evtSource.addEventListener("message", function(event) {
console.log("message event");
});
evtSource.addEventListener("stringEvent", function(event) {
console.log("received ping event");
console.log("event.data: " + event.data);
});
evtSource.onerror = function(err) {
console.error("EventSource failed:", JSON.stringify(err));
};
}
This is our server code... @Path("ssetest") public class SSETestService extends SecureService {
@GET
@Path("/test")
@Produces("text/event-stream")
public void runTest(@Context Sse sse, @Context SseEventSink sseEventSink)
{
int lastEventId = 0;// ..;
while (lastEventId < 10) {
OutboundSseEvent stringEvent = sse.newEventBuilder()
.name("" + lastEventId)
.mediaType(MediaType.APPLICATION_JSON_TYPE)
.data("hello world")
.id(String.valueOf(lastEventId))
.reconnectDelay(4000) // .comment("price change")
.build();
sseEventSink.send(stringEvent);
lastEventId++;
TimeUnit.SECONDS.sleep(1);
}
}
}
Browser console output...
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/iR57U.png