HTML5 – Server-sent events

Server-sent events (SSE) is a technique for sending data from a server to a web application in real-time. HTML5 introduced the EventSource interface, which allows web applications to receive server-sent events.

To use server-sent events, you can use the EventSource constructor to create a new event source object:

var source = new EventSource('/events');

In this example, the EventSource constructor is used to create a new event source object that connects to the /events endpoint on the server.

To receive data through the event source, you can use the onmessage event handler of the event source object:

source.onmessage = function(event) {
  console.log(event.data); // Outputs 'Hello client!'
};

In this example, the onmessage event handler is called when the server sends an event, and the event object passed to the event handler has a data property that contains the data of the event.

Here is an example of how to use server-sent events to receive data in real-time:

var source = new EventSource('/events');

// Receive an event from the server
source.onmessage = function(event) {
  console.log(event.data); // Outputs 'Hello client!'
};

// Close the event source when the page is unloaded
window.addEventListener('beforeunload', function() {
  source.close();
});

In this example, the EventSource constructor is used to create a new event source object that connects to the /events endpoint on the server. The onmessage event handler is called when the server sends an event, and the event object passed to the event handler has a data property that contains the data of the event. The close method is used to close the event source when the page is unloaded.