How does an SSE API work in HTML?
An SSE connection is established once the client initiates the communication with the server. The SSE API uses a JavaScript EventSource Object to which a URL of an endpoint is passed to the server using a regular HTTP request like GET, POST, etc.
Then the client receives the messages using the data streams over regular intervals of time.
(NOTE: You can see the messages during the server-client communication by pressing Ctrl + F12 key on your system ).
But ever wondered what would happen if the client doesn’t communicate and the server is trying to communicate with the client for a long period of time even though the connection is stable? In such a case, the SSE API will decide to leave the HTTP response as it has been open for a long time. It can also be closed if the client explicitly closes it.
Implementation using SSE API
The SSE API uses an EventSource interface with all the features/methods defined inside it, such as connecting to the servers, sending data, handling errors, termination of the connection, etc.
Let’s look at how the events are sent and received from the server using SSE API.
Events received from Server
New EventSource object is created to establish a persistent connection to which a script URL is passed using which events will be generated.
The messages can now be received using an eventHandler
CODE
Description: The code demonstrates how SSE API is used in HTML and automatically sends or updates the events on the client’s page.
<!DOCTYPE html>
<html>
<body>
<head>
<title>SSE_API_Receiving_Server_Events</title>
</head>
<h1 style="background-color: red;">Receiving Server Events</h1>
<div id="result"></div>
<script>
// if the browser supports the EventSource interface in the SSE
// API
if(typeof(EventSource) !== "undefined") {
// instantiating an object of EventSource which will sent the
// updates
var source = new EventSource("demo_sse.php");
//onmessage Event will occur when any update/message is received
source.onmessage = function(event) {
// update the result innerHTML
document.getElementById("result").innerHTML += event.data + "<br>";
};
} else {
document.getElementById("result").innerHTML = "Bad Luck! Your browser Doesn't support the SSE API";
}
</script>
</body>
</html>
The output of the above code:
The above code can be summarised as:
- Check if the browser supports the EventSource interface.
- Instantiating the EventSource object bypassing the server script URL
- Define the event handler to receive the server message and update it on the client’s page.
Events sent from Server
The server-side script sends events in the form of text/event-stream. Each notification sent is enclosed between 2 newline characters.
If you read the above code carefully, we have passed the URL demo_sse.php inside the EventSource object instantiated. Let’s see how this file is implemented and how events are sent from the Server.
<!DOCTYPE html>
<html>
<body>
<head>
<title>SSE_API_Receiving_Server_Events</title>
</head>
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$time = date('r');
echo "data: The server time is: {$time}\n\n";
flush();
?>
</body>
</html>
The above code is explained as follows:
- First, we mention the header-type, i.e. text/event-stream, and set the cache control to ‘no-cache’ as the page shouldn’t cache.
- If you see the output on the page of the previous code, you will see the line starting from “data:”. We have explicitly mentioned in our file to echo date.
- Finally, flush out the data onto the webpage.
Handling the Errors
In case of any errors, for example, network issues, network timeouts, access control issues, etc. They are handled by using an onerror call back on the EventSource object.
source.onerror = function(error) {
console.error("EventSource failed:", err);
};
You can also try this code with Online Javascript Compiler
Run Code
How do we use SSE API in HTML?
SSE API is used in the following scenarios:
- When we want a communication protocol that allows unidirectional communication without adding additional load over the server.
- When we want to use real-time streaming of data using HTTP-based methods.
SSE API is used in the following:
-
It’s being used to update the live scores/points/tables regularly.
- To refresh the feed of an application like Facebook, Twitter, etc.
- News updates
- Stock Price Updations
Challenges faced using SSE API in HTML
Some of the challenges faced are:
- It's a unidirectional way of using the SSE API, with no way of sending messages from a client to a server except at the time of connection.
- It doesn’t allow the server to know immediately if the connection is lost at the client-side.
Frequently asked questions
Question) Are SSE’s suitable in bidirectional communications?
Answer) Different protocols are used which serve different purposes according to the nature of real-time messaging and streaming data. Hence Web sockets are generally used for bidirectional communication.
Question) What is an Event Stream?
Answer) It’s a stream of text data encoded in UTF-8, and messages in the event stream are separated using 2 newline characters.
Question) Why is the SSE API useful?
Answer) An SSE API uses the event streams by subscribing to the Javascript datastreams to update the DOM objects on the client's web page and automatically sends events to the client’s browser.
Key takeaways
In a nutshell, in this blog, we covered the topic of Server-Sent Events(SSEs) in HTML in depth. We touched on various topics like the working of Server-Sent Events(SSEs) in HTML and when it should be used, with its limitations, and understood all of it using sample code. We also discussed its uses and what can be done and what can’t be done.
I hope you all could gain in-depth knowledge about the Server-Sent Events(SSEs) in HTML and understand the topic clearly. If you want to learn more exciting stuff, you can enroll in our top-tier courses taught by the best faculty to unleash your learning potential.
Happy Leaning Ninja!