Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
communitycreator

What are HTTP server-sent events?

Siddharth Singh

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.
Server sent events

Applications of server-sent events

  • Stock price updates are a good use case for SSEs, as the server has to send frequent updates to the client.

  • SSEs can also be used for server-monitoring services.

  • Real-time social media feeds, news updates, or alerts can also be updated using server-sent events.

RELATED TAGS

javascript
communitycreator
RELATED COURSES

View all Courses

Keep Exploring