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.
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. Theonmessage
handler is called if no event name is specified for a message.
- 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
data
- The data field for the message. When the
EventSource
receives multiple consecutive lines that begin withdata:
, it concatenated them, inserting a newline character between each one.
- The data field for the message. When the
id
- The event ID to set the
EventSource
object's last event ID value.
- The event ID to set the
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
There are currently no comments for this article.