<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Live Feed Client</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
#feed {
border: 1px solid #ccc;
padding: 10px;
height: 400px;
overflow-y: auto;
background-color: #f5f5f5;
}
.event {
margin: 5px 0;
padding: 10px;
background-color: white;
border-radius: 5px;
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}
.connected { border-left: 4px solid #4CAF50; }
.update { border-left: 4px solid #2196F3; }
.manual { border-left: 4px solid #FF9800; }
.controls {
margin-top: 20px;
}
button {
padding: 10px 20px;
margin-right: 10px;
cursor: pointer;
}
#status {
margin-top: 10px;
font-weight: bold;
}
</style>
</head>
<body>
<h1>Live Feed Demo</h1>
<div id="status">Disconnected</div>
<div id="feed"></div>
<div class="controls">
<button onclick="connect()">Connect</button>
<button onclick="disconnect()">Disconnect</button>
<button onclick="triggerEvent()">Trigger Manual Event</button>
<button onclick="clearFeed()">Clear Feed</button>
</div>
<script>
let eventSource = null;
const feed = document.getElementById('feed');
const status = document.getElementById('status');
function connect() {
if (eventSource) {
eventSource.close();
}
eventSource = new EventSource('http://localhost:3000/live-feed');
eventSource.onopen = () => {
status.textContent = 'Connected';
status.style.color = 'green';
};
eventSource.onmessage = (event) => {
const data = JSON.parse(event.data);
addEventToFeed(data);
};
eventSource.onerror = (error) => {
status.textContent = 'Connection Error';
status.style.color = 'red';
console.error('SSE Error:', error);
};
}
function disconnect() {
if (eventSource) {
eventSource.close();
eventSource = null;
status.textContent = 'Disconnected';
status.style.color = 'black';
}
}
function addEventToFeed(data) {
const eventDiv = document.createElement('div');
eventDiv.className = `event ${data.type}`;
const timestamp = new Date(data.timestamp).toLocaleTimeString();
let content = `<strong>${timestamp}</strong> - Type: ${data.type}`;
if (data.data) {
content += `<br>Data: ${JSON.stringify(data.data)}`;
}
if (data.message) {
content += `<br>Message: ${data.message}`;
}
eventDiv.innerHTML = content;
feed.insertBefore(eventDiv, feed.firstChild);
// Keep only last 50 events
while (feed.children.length > 50) {
feed.removeChild(feed.lastChild);
}
}
function clearFeed() {
feed.innerHTML = '';
}
async function triggerEvent() {
try {
const response = await fetch('http://localhost:3000/trigger-event', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
message: 'User triggered event',
priority: 'high'
})
});
const result = await response.json();
console.log('Event triggered:', result);
} catch (error) {
console.error('Error triggering event:', error);
}
}
// Auto-connect on page load
window.onload = () => connect();
</script>
</body>
</html>
// enhanced-server.js
const express = require('express');
const cors = require('cors');
const app = express();
const PORT = 3000;
app.use(cors());
app.use(express.json());
// Store clients by feed type
const feedClients = new Map();
// Initialize feed types
const feedTypes = ['news', 'stocks', 'weather', 'notifications'];
feedTypes.forEach(type => feedClients.set(type, new Set()));
// SSE endpoint with feed type parameter
app.get('/live-feed/:feedType', (req, res) => {
const { feedType } = req.params;
if (!feedClients.has(feedType)) {
return res.status(400).json({ error: 'Invalid feed type' });
}
// SSE headers
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
const client = {
id: Date.now(),
response: res,
feedType
};
feedClients.get(feedType).add(client);
// Send welcome message
res.write(`data: ${JSON.stringify({
type: 'connected',
feedType,
timestamp: new Date()
})}\n\n`);
console.log(`Client ${client.id} connected to ${feedType} feed`);
req.on('close', () => {
feedClients.get(feedType).delete(client);
console.log(`Client ${client.id} disconnected from ${feedType} feed`);
});
});
// Broadcast to specific feed
function broadcastToFeed(feedType, data) {
const clients = feedClients.get(feedType);
if (!clients) return;
const message = `data: ${JSON.stringify(data)}\n\n`;
clients.forEach(client => {
client.response.write(message);
});
}
// Simulate different feed data
const feedGenerators = {
news: () => ({
type: 'news',
headline: `Breaking: ${['Tech', 'Sports', 'Politics'][Math.floor(Math.random() * 3)]} Update`,
summary: 'Lorem ipsum dolor sit amet...',
timestamp: new Date()
}),
stocks: () => ({
type: 'stocks',
symbol: ['AAPL', 'GOOGL', 'MSFT'][Math.floor(Math.random() * 3)],
price: (100 + Math.random() * 50).toFixed(2),
change: (Math.random() * 10 - 5).toFixed(2),
timestamp: new Date()
}),
weather: () => ({
type: 'weather',
temperature: Math.floor(60 + Math.random() * 30),
condition: ['Sunny', 'Cloudy', 'Rainy'][Math.floor(Math.random() * 3)],
timestamp: new Date()
}),
notifications: () => ({
type: 'notifications',
message: `New notification at ${new Date().toLocaleTimeString()}`,
priority: ['low', 'medium', 'high'][Math.floor(Math.random() * 3)],
timestamp: new Date()
})
};
// Generate feed updates at different intervals
setInterval(() => {
broadcastToFeed('news', feedGenerators.news());
}, 5000);
setInterval(() => {
broadcastToFeed('stocks', feedGenerators.stocks());
}, 1000);
setInterval(() => {
broadcastToFeed('weather', feedGenerators.weather());
}, 10000);
setInterval(() => {
broadcastToFeed('notifications', feedGenerators.notifications());
}, 3000);
// Get feed statistics
app.get('/feed-stats', (req, res) => {
const stats = {};
feedClients.forEach((clients, feedType) => {
stats[feedType] = clients.size;
});
res.json(stats);
});
app.listen(PORT, () => {
console.log(`Enhanced SSE server running on http://localhost:${PORT}`);
});