HTML SSE (Server-Sent Events) is a web technology that enables a server to send real-time updates to a web page over a single, long-lived HTTP connection. SSE provides a unidirectional channel from the server to the client, allowing the server to push events to the client as they occur.
To implement SSE, you need a server that supports SSE and a client-side component to handle the received events. Here's an example of how to use SSE in HTML:
1. Server-side (e.g., using Node.js with Express):
javascript
const express = require('express');
const app = express();
// Route to handle SSE connections
app.get('/sse', (req, res) => {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
// Send initial SSE event
res.write('data: SSE connection established\n\n');
// Send updates at regular intervals
const intervalId = setInterval(() => {
const eventData = { /* data to send to the client */ };
res.write('data: ' + JSON.stringify(eventData) + '\n\n');
}, 1000);
// Clean up the SSE connection when the client disconnects
req.on('close', () => {
clearInterval(intervalId);
});
});
app.listen(3000, () => {
console.log('Server listening on port 3000');
});
2. Client-side (HTML and JavaScript):
html
<!DOCTYPE html>
<html>
<head>
<title>SSE Example</title>
</head>
<body>
<script>
const eventSource = new EventSource('/sse');
// Event handler for receiving SSE events
eventSource.onmessage = function(event) {
const eventData = JSON.parse(event.data);
// Process the received data
//
};
</script>
</body>
</html>
In this example, the server-side code sets up a route ("/sse") to handle SSE connections. When a client establishes an SSE connection, the server sets the necessary headers to indicate the response contains event-stream data. It sends an initial SSE event to confirm the connection establishment and then sends periodic events containing updates. The server cleans up the SSE connection when the client disconnects.
On the client-side, the JavaScript code creates a new `EventSource` object, specifying the SSE route ("/sse"). It sets the `onmessage` event handler to handle incoming SSE events. Within the event handler, the received event data can be processed as needed.
SSE is a convenient way to achieve server-to-client real-time communication in web applications, especially when you want the server to push updates to the client without requiring constant client requests.
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc