-
Hajipur, Bihar, 844101
Server-Sent Events (SSE) allow a web page to receive automatic updates from a server via an HTTP connection. Unlike WebSockets, SSE is unidirectional — data flows from the server to the client only.
SSE is useful for real-time notifications, news feeds, or live updates where the server pushes data to the browser continuously.
The client opens a persistent HTTP connection to the server using an EventSource
object in JavaScript.
The server keeps the connection open and sends messages whenever new data is available.
The client listens for messages using event handlers.
const http = require('http');
http.createServer((req, res) => {
if (req.url === '/events') {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
let counter = 0;
const interval = setInterval(() => {
counter++;
res.write(`data: Message number ${counter}\n\n`);
if (counter === 5) {
clearInterval(interval);
res.end();
}
}, 1000);
} else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(`<html><body>
<script>
const evtSource = new EventSource('/events');
evtSource.onmessage = function(event) {
document.body.innerHTML += '<p>' + event.data + '</p>';
};
</script>
</body></html>`);
}
}).listen(3000);
const eventSource = new EventSource('path_to_server');
eventSource.onmessage = function(event) {
console.log('New message:', event.data);
};
eventSource.onerror = function(event) {
console.error('EventSource failed:', event);
};
SSE uses the text/event-stream
content type.
Each message must be prefixed with data:
and end with two newlines (\n\n
).
SSE works over HTTP/HTTPS but requires a persistent connection.
Supported by most modern browsers (except IE).
SSE is simpler than WebSocket but only supports server-to-client streaming.
Q1. Create an HTML page that listens to server-sent events and displays messages live.
Q2. Implement a Node.js server sending SSE messages every 2 seconds.
Q3. Handle SSE errors with onerror
event on client-side.
Q4. Stop receiving events after a certain count using JavaScript.
Q5. Display live stock prices or news feed using SSE.
Q6. Send custom events with event names using event:
prefix.
Q7. Implement reconnect logic for SSE connection loss.
Q8. Use SSE to update a live chat window from server messages.
Q9. Customize message format using multi-line messages.
Q10. Compare SSE with WebSockets for use cases.
Q1: What protocol do Server-Sent Events use?
Q2: Which JavaScript object is used to receive SSE messages?
Q3: How is each SSE message formatted?
Q4: SSE is:
Q5: Which HTTP content-type is used for SSE?
Q6: Which event handler listens for incoming messages?
Q7: How does SSE handle connection interruptions?
Q8: What is the maximum number of event streams a client can open?
Q9: Which is NOT true about SSE?