DEV Community

mixbo
mixbo

Posted on

1 2

What is Server Sent Event

Alt Text

The Server Sent Events specification describes a built-in class EventSource, that keeps connection with the server and allows to receive events from it. similar to WebSocket it’s simpler. In many applications, the power of WebSocket is a little bit too much.

What difference:

  • One-directional: only server sends data

  • Only text

  • Regular HTTP

Getting messages

  1. To start receiving messages, we just need to create new EventSource(url).
  2. The browser will connect to url and keep the connection open, waiting for events.
  3. The server should respond with status 200 and the header Content-Type: text/event-stream
let eventSource = new EventSource("/events/channel");
eventSource.onmessage = function(event) {
  console.log("New message", event.data);
};
Enter fullscreen mode Exit fullscreen mode

Reconnection

Upon creation, new EventSource connects to the server, and if the connection is broken – reconnects. that’s very convenient, as we don’t have to care about it.

Close

let eventSource = new EventSource(...);
eventSource.close();
Enter fullscreen mode Exit fullscreen mode

Event types

By default EventSource object generates three events:

  • message – a message received, available as event.data.
  • open – the connection is open.
  • error – the connection could not be established, e.g. the server returned HTTP 500 status.

Hope it can help you :)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay