Server Sent Events

I want to read about server sent events because I need to either use web sockets or server sent events to implement push notifications.

Date Created:
1 47

References



Related


  • Server Push
    • HTTP/2 Server Push is an optional feature of the HTTP/2 and HTTP/3 network protocols that allows servers to send resources to a client before the client requests them. Server Push is a performance technique aimed at reducing latency by sending resources to a client preemptively before it knows they will be needed. In practice, Server Push frequently results in wasted bandwidth because the server rarely knows which resources are already loaded by the client and transmits the same resource multiple times, resulting in slowdowns if the resources being pushed complete for bandwidth with resources that were requested.
  • HTML Living Standard
    • Hypertext Markup Language (HTML) is the standard markup language for documents designed to be displayed in a web browser. It defines the content and structure of web content. It is often assisted by technologies such as Cascading style Sheets (CSS) and scripting languages such as JavaScript, a programming language.
  • WHATWG
    • The Web Hypertext Application Technology Working Group (WHATWG) is a community of people interested in evolving HTML and related technologies. The WHATWG was founded by individuals form Apple Inc. the Mozilla Foundation and Opera Software, leading Web browser vendors in 2004. WHATWG is responsible for maintaining multiple web-related technical standards, including the specifications for the Hypertext Markup Language and the Document Object Module (DOM). The central organizational membership and control of WHATWG – its "Steering Group" – consists of Apple, Mozilla, Google, and Microsoft. WHATWG community members work with the editor of the specifications to ensure correct implementation.
  • media type
    • In information and communications technology, a media type, content type, or MIME type is a two-part identifier for file formats and content formats, Their purpose is comparable to filename extensions and uniform type identifiers, in that they identify the intended data format. They are mainly used by technologies underpinning the Internet, and also used n Linux desktop systems.


Notes


Server-Sent Events (SSE) is a server push technology enabling a client to receive automatic updates from a server via an HTTP connection, and describes how servers can initiate data transmission towards clients once an initial client connection has been established. They are commonly used to send message updates or continuous data streams to a browser client and designated to enhance native, cross-browser streaming through a JavaScript API called Event Source through which a client requests a particular URL in order to receive an event stream. The EventSource API is standardized as part of HTML Living Standard by the WHATWG. The media type for SSE us text/event-stream.

Developing an application that uses server-sent events is straightforward. You'll need a bit of code on the server to stream events to the front-end, but the client side code works almost identically to websockets in part of handling incoming events. This is a one-way connection, so you can't send events from a client to a server.

Receiving events from the server

The server-sent event API is contained in the EventSource interface. To open a connection to the server to begin receiving events from it, create a new EventSource object with the URL of a script that generates the events:

const evtSource = new EventSource("sse-demo.php");

If the event generator script is hosted on a different origin, a new EventSource object should be created with both the URL and an options directory:

const evtSource = new EventSource("//api.example.com/sse-demo.php", {
withCredentials: true,
});

Messages sent form the server that don't have an event field are received as message events. To receive message events, attach a handler for the message event:

evtSource.onmessage = (event) => {
const newElement = document.createElement("li");
const eventList = document.getElementById("list");

newElement.textContent = `message: ${event.data}`;
eventList.appendChild(newElement);
};

The code listens for incoming message events and appends the message text to a list in the document's HTML.

Listening for Custom Events

Messages form the server that do have an event filed defined are received as events with the name given in event.

evtSource.addEventListener("ping", (event) => {
const newElement = document.createElement("li");
const eventList = document.getElementById("list");
const time = JSON.parse(event.data).time;
newElement.textContent = `ping at ${time}`;
eventList.appendChild(newElement);
});

This code will be called whenever the server sends a message with the event filed set to ping; it then parses the JSON in the data field and inputs that information.

Sending events from the server

The server-side script that sends events needs to respond using the MIME type text/event-stream. Each notification is sent as a block of text terminated by a pair of newlines. See Event Stream Format

You can catch errors with the evtSource.onerror callback, and you close the connection between the client and the server with the evtSource.close() method.

Event Stream Format

The event stream is a simple stream of text data which must be encoded using UTF-8. Messages in the event stream are separated by a pair of newline characters. A colon as the first character of a line is in essence a comment, and is ignored.
Each message consists of one or more lines of text listing the fields for that message. Each field is represented by the field name, followed by a colon, followed by the text data for that field's value.

Fields

Each message received has some combination of the following fields, one per line:

  • event
    • A string identifying the type of event described. If supplied, an event will be dispatched on the browser to the listener for the specified event name; the website source code should use addEventListener() to listen for named events. The onmessage handler is called if no event name is specified for a message.
  • data
    • The data field for the message. When the EventSource receives multiple consecutive lines that begin with data:, it concatenated them, inserting a newline character between each one.
  • id
    • The event ID to set the EventSource object's last event ID value.
  • retry
    • The reconnection time. If the connection to the server is lost, the browser will wait for the specified time before attempting to reconnect. This must be an integer, specifying the reconnection time in milliseconds. If a non-integer value is specified, the field is ignored.

Comments

You have to be logged in to add a comment

User Comments

Insert Math Markup

ESC
About Inserting Math Content
Display Style:

Embed News Content

ESC
About Embedding News Content

Embed Youtube Video

ESC
Embedding Youtube Videos

Embed TikTok Video

ESC
Embedding TikTok Videos

Embed X Post

ESC
Embedding X Posts

Embed Instagram Post

ESC
Embedding Instagram Posts

Insert Details Element

ESC

Example Output:

Summary Title
You will be able to insert content here after confirming the title of the <details> element.

Insert Table

ESC
Customization
Align:
Preview:

Insert Horizontal Rule

#000000

Preview:


View Content At Different Sizes

ESC

Edit Style of Block Nodes

ESC

Edit the background color, default text color, margin, padding, and border of block nodes. Editable block nodes include paragraphs, headers, and lists.

#ffffff
#000000

Edit Selected Cells

Change the background color, vertical align, and borders of the cells in the current selection.

#ffffff
Vertical Align:
Border
#000000
Border Style:

Edit Table

ESC
Customization:
Align:

Upload Lexical State

ESC

Upload a .lexical file. If the file type matches the type of the current editor, then a preview will be shown below the file input.

Upload 3D Object

ESC

Upload Jupyter Notebook

ESC

Upload a Jupyter notebook and embed the resulting HTML in the text editor.

Insert Custom HTML

ESC

Edit Image Background Color

ESC
#ffffff

Insert Columns Layout

ESC
Column Type:

Select Code Language

ESC
Select Coding Language

Insert Chart

ESC

Use the search box below

Upload Previous Version of Article State

ESC