Server-sent events enable servers to push data to the web client using a long-term persistent connection with the server. This connection is unidirectional, so clients cannot send events to a server.
Server-sent events use JavaScript’s EventSource API to continuously push messages to the client.
For example, the following code creates an EventSource
object and registers an event listener:
var source = new EventSource('serverUpdates.aspx');
source.onmessage = function (event) {
alert(event.data);
};
On the server-side, the script (“serverUpdates.aspx” in this case) sends messages in the form of text/event-stream MIME type. Each notification is sent as a block of text terminated by a pair of newlines:
data: message 1.
data: message 2.
data: message 3.