I am using jersey 2 to implement server sent . when i do a curl i am getting proper response back with a one second of delay as expected. But when i try to use event source from client side , it waits for all the events to get completed and then onmessage is called. Also it repeatedly making server calls .. below is the server side and client side code i am using. Server side jersey code
@GET
@Path("/serverSentCheck")
@Produces(SseFeature.SERVER_SENT_EVENTS)
@ManagedAsync
public EventOutput serverSentCheck() {
final EventOutput eventOutput = new EventOutput();
new Thread(new Runnable() {
@Override
public void run() {
try {
for (int i = 0; i < 5; i++) {
Thread.sleep(1000);
final OutboundEvent.Builder eventBuilder
= new OutboundEvent.Builder();
// eventBuilder.name("message-to-client");
eventBuilder.data(String.class,
"Hello world " + i + "!");
final OutboundEvent event = eventBuilder.build();
eventOutput.write(event);
}
} catch (IOException | InterruptedException e) {
throw new RuntimeException(
"Error when writing the event.", e);
} finally {
try {
eventOutput.close();
} catch (IOException ioClose) {
throw new RuntimeException(
"Error when closing the event output.", ioClose);
}
}
}
}).start();
return eventOutput;
}
client side eventsource code
var source = new EventSource(" https://localhost:7080/api/v1/service/serverSentCheck");
source.onmessage = function(event) {
console.log(event.data);
document.getElementById("result").innerHTML += event.data + "<br>";
};
Curl command thats working properly
curl --insecure -H "Accept:text/event-stream" https://localhost:7080/api/v1/service/serverSentCheck