Invoking the SSE service from JavaScript

It's very common to invoke SSE services from JavaScript code in a browser to update the page as the keep coming from the service. Most modern browsers support the SSE protocol and provide the EventSource object, which makes invoking an SSE service very simple.

To invoke our forecast service, we only need the following code:

var source = new EventSource("http://localhost:8080/forecast-service-async/" +
"smartcity/forecast");
source.onmessage = function (event) {
if (event.lastEventId === "completed") {
source.close();
} else {
alert("Received: " + event.data);
}
};
The preceding code will do the following:
  • Create an instance of the EventSource object and immediately open a connection to the SSE service.
  • Provide a function to handle messages as the onmessage property of our EventSource instance.
  • The handler validates the value of lastEventId to detect the final message, and closes the EventSource object when the final message is received.
If a browser doesn't provide the EventSource object with access to SSE services, it's possible to use a polyfill library, which will seamlessly add it. A collection of various polyfill libraries can be found in a wiki of the Modernizr project at https://github.com/Modernizr/Modernizr/wiki.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.128.205.21