I have created the following class running on the server side on Glassfish:
@Path("events")
public class SseResource {
@GET
@Produces(SseFeature.SERVER_SENT_EVENTS)
public EventOutput getServerSentEvents() {
final EventOutput eventOutput = new EventOutput();
// new Thread(new Runnable() {
// @Override
// public void run() {
try {
for (int i = 0; i < 10; i++) {
// ... code that waits 1 second
final OutboundEvent.Builder eventBuilder
= new OutboundEvent.Builder();
eventBuilder.name("message-to-client");
eventBuilder.data(String.class,
"Hello world ");
final OutboundEvent event = eventBuilder.build();
eventOutput.write(event);
}
} catch (IOException 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;
}
}
I initialized the class from the resource here:
resources.add(WebServicesPublic.SseResource.class);
And then I created an HTML page that calls the server like so:
<html>
<body>
Time: <span id="foo"></span>
<br><br>
<button onclick="start()">Start</button>
<script type="text/javascript">
function start() {
var eventSource = new EventSource("webresources/events");
eventSource.addEventListener("message-to-client", msgClient, false);
eventSource.onmessage = function(event) {
document.getElementById('foo').innerHTML = event.data;
};
}
function msgClient(event)
{
document.getElementById('foo').innerHTML = event.data;
}
</script>
</body>
</html>
However, no events ever show up in the browser. I am running Glassfish 4. Anybody have any idea why it doesn't work? If I set a breakpoint in the server code, it does get hit. However, similar breakpoints in Chrome reveal no events received.
Does it work if you comment out eventBuilder.name("message-to-client");
? Without that line events will go to the default message handler, which is called "message". (Event names should work, but get the default case working first.)
Also, I don't think onmessage
syntax works, so replace that line with:
eventSource.addEventListener('message',function(event){
document.getElementById('foo').innerHTML = event.data;
},false);
Also, make sure you have the developer tools (network tab) open under Chrome. Your connection is lasting 10 seconds, then the server-side is closing it. Chrome will wait about 3 seconds, the reconnect. So under the network tab, after a while, you should see rows start to stack up, each 10 seconds long. (And, if not, there should be a clue under the console.log.)