Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How do you receive server-sent event notifications in JavaScript?
Server-sent events (SSE) provide a unidirectional communication channel between server and client. When you only need to send data from server to client, SSE offers an efficient alternative to polling or WebSockets.
Server-sent events work by establishing a persistent connection where the server pushes data to the client. The server can be any backend technology like Node.js, PHP, or Ruby. When the server sends data, a 'message' event fires on the client-side, which can be handled with event listeners.
How Server-Sent Events Work
The process involves three main steps:
- Client establishes connection using EventSource
- Server maintains persistent connection and sends data
- Client receives data through message events
Client-Side Implementation
First, create the client-side code to establish connection and listen for events:
<html>
<body>
<h2>Server-Sent Events Demo</h2>
<div id="output"></div>
<script>
const output = document.getElementById('output');
// Create EventSource connection
const source = new EventSource('http://localhost:5000/subscribe');
// Listen for messages from server
source.addEventListener('message', function(event) {
output.innerHTML += "Received: " + event.data + "<br>";
});
// Handle connection errors
source.addEventListener('error', function(event) {
console.log('Connection error:', event);
});
</script>
</body>
</html>
Server-Side Implementation (Node.js)
Create a Node.js server that sends periodic updates to connected clients:
Setup: Install required packages:
npm init -y npm install express cors
Server Code (app.js):
const express = require("express");
const cors = require("cors");
const app = express();
app.use(cors());
const PORT = 5000;
let allConnectedClients = [];
async function subscribeClient(req, res) {
// Set SSE headers
const headers = {
"Content-Type": "text/event-stream",
"Connection": "keep-alive",
"Cache-Control": "no-cache"
};
res.writeHead(200, headers);
// Add client to active connections
const clientId = Date.now();
const client = { id: clientId, res };
allConnectedClients.push(client);
console.log(`Client connected: ${clientId}`);
// Sample data to send
const messages = [
"Hello from server!",
"Processing data...",
"Update available",
"Task completed",
"New notification"
];
let counter = 0;
// Send periodic updates
const interval = setInterval(() => {
const randomMessage = messages[Math.floor(Math.random() * messages.length)];
res.write(`data: ${randomMessage} (${++counter})<br><br>`);
}, 3000);
// Handle client disconnect
req.on('close', () => {
console.log(`Client disconnected: ${clientId}`);
clearInterval(interval);
allConnectedClients = allConnectedClients.filter(c => c.id !== clientId);
});
}
// SSE endpoint
app.get("/subscribe", subscribeClient);
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Run the server:
node app.js
Key Features
| Feature | Server-Sent Events | Polling |
|---|---|---|
| Connection Type | Persistent | Request per update |
| Server Load | Low | High |
| Real-time Updates | Yes | Delayed |
| Browser Support | Modern browsers | All browsers |
Error Handling
Always implement proper error handling for robust applications:
const source = new EventSource('/subscribe');
source.addEventListener('open', function() {
console.log('Connection opened');
});
source.addEventListener('error', function(event) {
if (event.readyState == EventSource.CLOSED) {
console.log('Connection closed');
} else {
console.log('Connection error occurred');
}
});
Conclusion
Server-sent events provide an efficient way to push real-time updates from server to client. Unlike polling, SSE maintains a persistent connection and only sends data when needed, reducing server load and providing instant updates.
