This is a comprehensive request to build a live sports scores system with SSE (Server-Sent Events) or efficient long-polling, with delta updates to only show changes. Let me create a complete implementation.
Key requirements:
- Live sports scores using SSE or long-polling
- Delta updates - track previous state and only show changes
- Efficient filtering to minimize console noise
- Goal notifications and other significant changes
I'll provide:
- Backend with mock sports data and both SSE and long-polling endpoints
- Frontend client with both SSE and long-polling implementations
- Delta update logic to track state changes
- Efficient notification system
Let me create a production-ready solution:
Live Sports Scores with Delta Updates
I'll create a comprehensive system with both SSE and long-polling, with efficient delta updates.
1. Backend with Express (SSE & Long-Polling)
// server.js
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());
app.use(express.json());
app.use(express.static('public'));
// =====================================================
// SIMULATED SPORTS DATA
// =====================================================
class SportsDataManager {
constructor() {
this.games = this.initializeGames();
this.lastUpdateTime = Date.now();
}
initializeGames() {
return {
game1: {
id: 'game1',
league: 'NFL',
homeTeam: { name: 'Lakers', score: 0 },
awayTeam: { name: 'Warriors', score: 0 },
status: 'not_started',
quarter: 0,
time: '0:00',
lastUpdate: Date.now(),
possession: 'home',
timeouts: { home: 3, away: 3 },
},
game2: {
id: 'game2',
league: 'NBA',
homeTeam: { name: 'Celtics', score: 0 },
awayTeam: { name: 'Heat', score: 0 },
status: 'not_started',
quarter: 0,
time: '0:00',
lastUpdate: Date.now(),
possession: 'away',
timeouts: { home: 3, away: 3 },
},
game3: {
id: 'game3',
league: 'NFL',
homeTeam: { name: 'Chiefs', score: 0 },
awayTeam: { name: 'Bills', score: 0 },
status: 'not_started',
quarter: 0,
time: '0:00',
lastUpdate: Date.now(),
possession: 'home',
timeouts: { home: 3, away: 3 },
},
};
}
updateGames() {
const gameIds = Object.keys(this.games);
const indexToUpdate = Math.floor(Math.random() * gameIds.length);
const gameId = gameIds[indexToUpdate];
const game = this.games[gameId];
// Randomly decide what to update
const updateType = Math.random();
if (updateType < 0.1 && game.status === 'not_started') {
// 10% chance: Start game
game.status = 'in_progress';
game.quarter = 1;
return { type: 'game_started', gameId, game };
}
if (game.status === 'in_progress') {
// Update time
const timeParts = game.time.split(':');
let mins = parseInt(timeParts[0]);
let secs = parseInt(timeParts[1]);
secs += Math.floor(Math.random() * 30) + 5;
if (secs >= 60) {
mins += 1;
secs -= 60;
}
if (updateType < 0.3) {
// 20% chance: Score!
const isHome = Math.random() > 0.5;
const points = Math.random() > 0.7 ? 3 : (Math.random() > 0.5 ? 2 : 1);
if (isHome) {
game.homeTeam.score += points;
} else {
game.awayTeam.score += points;
}
game.lastUpdate = Date.now();
return {
type: 'score_update',
gameId,
game,
event: {
team: isHome ? game.homeTeam.name : game.awayTeam.name,
points,
newScore: isHome ? game.homeTeam.score : game.awayTeam.score,
},
};
} else if (updateType < 0.5) {
// 20% chance: Change possession
game.possession = game.possession === 'home' ? 'away' : 'home';
game.lastUpdate = Date.now();
return {
type: 'possession_change',
gameId,
game,
event: {
team: game.possession === 'home' ? game.homeTeam.name : game.awayTeam.name,
},
};
} else if (updateType < 0.65 && (game.quarter < 4 || (game.league === 'NFL'))) {
// 15% chance: Quarter change
game.quarter += 1;
game.time = '0:00';
game.lastUpdate = Date.now();
if (game.quarter > 4) {
game.status = 'finished';
return {
type: 'game_finished',
gameId,
game,
event: {
finalScore: `${game.homeTeam.name} ${game.homeTeam.score} - ${game.awayTeam.score} ${game.awayTeam.name}`,
},
};
}
return {
type: 'quarter_change',
gameId,
game,
event: { quarter: game.quarter },
};
} else {
// Regular time update
game.time = `${mins}:${secs.toString().padStart(2, '0')}`;
game.lastUpdate = Date.now();
return { type: 'time_update', gameId, game };
}
}
return { type: 'no_change', gameId, game };
}
getGameSnapshot(gameId) {
return this.games[gameId] || null;
}
getAllGames() {
return this.games;
}
}
const sportsManager = new SportsDataManager();
// =====================================================
// SIMULATION LOOP
// =====================================================
setInterval(() => {
sportsManager.updateGames();
}, 2000); // Update every 2 seconds
// =====================================================
// SSE ENDPOINT
// =====================================================
const sseClients = new Set();
app.get('/api/sports/sse', (req, res) => {
console.log(`[SSE] New client connected: ${req.ip}`);
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
res.setHeader('Access-Control-Allow-Origin', '*');
// Send initial snapshot
const snapshot = sportsManager.getAllGames();
res.write(`data: ${JSON.stringify({
type: 'initial_snapshot',
data: snapshot,
})}\n\n`);
// Store client
const clientId = Date.now() + Math.random();
const client = { id: clientId, res, lastUpdate: Date.now() };
sseClients.add(client);
// Handle client disconnect
req.on('close', () => {
console.log(`[SSE] Client disconnected: ${req.ip}`);
sseClients.delete(client);
});
// Send heartbeat every 30 seconds
const heartbeat = setInterval(() => {
if (!client.res.writableEnded) {
client.res.write(':heartbeat\n\n');
} else {
clearInterval(heartbeat);
}
}, 30000);
});
// Broadcast updates to all SSE clients
function broadcastSSE(update) {
const message = `data: ${JSON.stringify(update)}\n\n`;
sseClients.forEach((client) => {
if (!client.res.writableEnded) {
client.res.write(message);
}
});
}
// =====================================================
// LONG-POLLING ENDPOINT
// =====================================================
app.get('/api/sports/poll', (req, res) => {
const lastSync = parseInt(req.query.lastSync || 0);
console.log(`[Poll] Request from ${req.ip}, lastSync: ${lastSync}`);
// Send immediately if we have updates since last sync
const games = sportsManager.getAllGames();
const updates = [];
Object.values(games).forEach((game) => {
if (game.lastUpdate > lastSync) {
updates.push({
type: 'game_update',
gameId: game.id,
data: game,
});
}
});
if (updates.length > 0) {
console.log(`[Poll] Sending ${updates.length} updates`);
return res.json({
success: true,
timestamp: Date.now(),
updates,
});
}
// Wait for updates (with timeout)
const pollTimeout = 30000; // 30 seconds
const startTime = Date.now();
const checkForUpdates = setInterval(() => {
const now = Date.now();
const games = sportsManager.getAllGames();
const newUpdates = [];
Object.values(games).forEach((game) => {
if (game.lastUpdate > lastSync) {
newUpdates.push({
type: 'game_update',
gameId: game.id,
data: game,
});
}
});
if (newUpdates.length > 0 || now - startTime > pollTimeout) {
clearInterval(checkForUpdates);
if (!res.writableEnded) {
res.json({
success: true,
timestamp: Date.now(),
updates: newUpdates,
});
}
}
}, 500); // Check every 500ms
// Cleanup on client disconnect
req.on('close', () => {
clearInterval(checkForUpdates);
});
});
// =====================================================
// REST ENDPOINTS
// =====================================================
app.get('/api/sports/games', (req, res) => {
res.json(sportsManager.getAllGames());
});
app.get('/api/sports/game/:id', (req, res) => {
const game = sportsManager.getGameSnapshot(req.params.id);
if (!game) {
return res.status(404).json({ error: 'Game not found' });
}
res.json(game);
});
// =====================================================
// EMIT UPDATES TO SSE CLIENTS
// =====================================================
setInterval(() => {
const update = sportsManager.updateGames();
if (update.type !== 'time_update' && update.type !== 'no_change') {
console.log(`[Broadcast] ${update.type} for game ${update.gameId}`);
broadcastSSE(update);
}
}, 2000);
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`\n🏆 Sports Server running on http://localhost:${PORT}\n`);
console.log('Endpoints:');
console.log(' SSE: http://localhost:3000/api/sports/sse');
console.log(' Poll: http://localhost:3000/api/sports/poll');
console.log(' REST: http://localhost:3000/api/sports/games\n');
});
2. SSE Client with Delta Updates
// public/sse-client.js
class SportsSSEClient {
constructor(options = {}) {
this.url = options.url || '/api/sports/sse';
this.eventSource = null;
this.previousState = new Map(); // Store previous game state
this.listeners = new Map(); // Event listeners
this.isConnected = false;
this.reconnectAttempts = 0;
this.maxReconnectAttempts = 10;
this.reconnectDelay = 3000;
this.options = {
logAllUpdates: options.logAllUpdates !== false,
filterMinorUpdates: options.filterMinorUpdates !== false,
notificationSoundEnabled: options.notificationSoundEnabled !== true,
...options,
};
}
connect() {
console.log('[SSE] Connecting...');
this.eventSource = new EventSource(this.url);
this.eventSource.addEventListener('message', (event) => {
this._handleMessage(event);
});
this.eventSource.addEventListener('error', (event) => {
this._handleError(event);
});
this.eventSource.onopen = () => {
console.log('[SSE] Connected successfully!');
this.isConnected = true;
this.reconnectAttempts = 0;
this._emit('connected');
};
}
_handleMessage(event) {
try {
const update = JSON.parse(event.data);
if (update.type === 'initial_snapshot') {
console.log('[SSE] Received initial snapshot');
this._processInitialSnapshot(update.data);
} else {
this._processUpdate(update);
}
} catch (error) {
console.error('[SSE] Parse error:', error.message);
}
}
_handleError(event) {
console.error('[SSE] Connection error:', event);
this.isConnected = false;
this._emit('disconnected');
this._attemptReconnect();
}
_attemptReconnect() {
if (this.reconnectAttempts < this.maxReconnectAttempts) {
this.reconnectAttempts++;
const delay = this.reconnectDelay * this.reconnectAttempts;
console.log(
`[SSE] Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts})`
);
setTimeout(() => {
this.eventSource?.close();
this.connect();
}, delay);
} else {
console.error('[SSE] Max reconnect attempts reached');
this._emit('reconnect_failed');
}
}
_processInitialSnapshot(games) {
Object.entries(games).forEach(([gameId, gameData]) => {
this.previousState.set(gameId, JSON.parse(JSON.stringify(gameData)));
});
}
_processUpdate(update) {
const { type, gameId, game, event } = update;
// Skip minor updates
if (
this.options.filterMinorUpdates &&
type === 'time_update'
) {
return;
}
// Calculate delta
const delta = this._calculateDelta(gameId, game);
// Store new state
this.previousState.set(gameId, JSON.parse(JSON.stringify(game)));
// Format notification
const notification = this._formatNotification(type, game, event, delta);
// Log and emit
this._logNotification(notification, type);
this._emit('update', { type, gameId, game, event, delta, notification });
// Trigger sound for important events
if (this._isImportantEvent(type) && this.options.notificationSoundEnabled) {
this._playNotificationSound(type);
}
}
_calculateDelta(gameId, newGame) {
const oldGame = this.previousState.get(gameId);
const delta = {};
if (!oldGame) return delta;
// Compare scores
if (oldGame.homeTeam.score !== newGame.homeTeam.score) {
delta.homeScoreChange = newGame.homeTeam.score - oldGame.homeTeam.score;
}
if (oldGame.awayTeam.score !== newGame.awayTeam.score) {
delta.awayScoreChange = newGame.awayTeam.score - oldGame.awayTeam.score;
}
// Compare status
if (oldGame.status !== newGame.status) {
delta.statusChange = { from: oldGame.status, to: newGame.status };
}
// Compare quarter
if (oldGame.quarter !== newGame.quarter) {
delta.quarterChange = { from: oldGame.quarter, to: newGame.quarter };
}
// Compare possession
if (oldGame.possession !== newGame.possession) {
delta.possessionChange = {
from: oldGame.possession,
to: newGame.possession,
};
}
return delta;
}
_formatNotification(type, game, event, delta) {
const timestamp = new Date().toLocaleTimeString();
const gameLabel = `${game.homeTeam.name} vs ${game.awayTeam.name}`;
switch (type) {
case 'game_started':
return `🎬 ${gameLabel} - GAME STARTED (${timestamp})`;
case 'score_update':
return `🏀 GOAL! ${event.team} scores ${event.points}pts! ` +
`(${game.homeTeam.name} ${game.homeTeam.score} - ${game.awayTeam.score} ${game.awayTeam.name}) - ${timestamp}`;
case 'quarter_change':
return `📊 ${gameLabel} - ${event.quarter === 5 ? 'OT' : `Q${event.quarter}`} (${timestamp})`;
case 'possession_change':
return `🔄 ${gameLabel} - Possession: ${event.team} (${timestamp})`;
case 'game_finished':
return `🏁 ${gameLabel} - FINAL: ${event.finalScore} (${timestamp})`;
case 'time_update':
return `⏱️ ${gameLabel} - ${game.time} in Q${game.quarter} (${timestamp})`;
default:
return `📢 ${gameLabel} - ${type} (${timestamp})`;
}
}
_isImportantEvent(type) {
return ['game_started', 'score_update', 'quarter_change', 'game_finished'].includes(type);
}
_logNotification(message, type) {
const colors = {
score_update: '\x1b[33m%s\x1b[0m', // Yellow
game_started: '\x1b[36m%s\x1b[0m', // Cyan
quarter_change: '\x1b[35m%s\x1b[0m', // Magenta
game_finished: '\x1b[32m%s\x1b[0m', // Green
possession_change: '\x1b[34m%s\x1b[0m', // Blue
time_update: '\x1b[90m%s\x1b[0m', // Gray
};
const format = colors[type] || '%s';
console.log(format, message);
}
_playNotificationSound(type) {
// Would implement actual sound here
if (type === 'score_update') {
console.log('🔊 GOAL HORN SOUND');
}
}
_emit(eventName, data) {
if (this.listeners.has(eventName)) {
this.listeners.get(eventName).forEach((callback) => {
callback(data);
});
}
}
on(eventName, callback) {
if (!this.listeners.has(eventName)) {
this.listeners.set(eventName, []);
}
this.listeners.get(eventName).push(callback);
}
off(eventName, callback) {
if (this.listeners.has(eventName)) {
const callbacks = this.listeners.get(eventName);
const index = callbacks.indexOf(callback);
if (index > -1) {
callbacks.splice(index, 1);
}
}
}
disconnect() {
console.log('[SSE] Disconnecting...');
if (this.eventSource) {
this.eventSource.close();
this.eventSource = null;
}
this.isConnected = false;
}
getGameState(gameId) {
return this.previousState.get(gameId);
}
getAllGames() {
const games = {};
this.previousState.forEach((game, gameId) => {
games[gameId] = game;
});
return games;
}
}
// Export for use
if (typeof module !== 'undefined' && module.exports) {
module.exports = SportsSSEClient;
}
3. Long-Polling Client with Delta Updates
// public/polling-client.js
class SportsPollingClient {
constructor(options = {}) {
this.url = options.url || '/api/sports/poll';
this.pollInterval = options.pollInterval || 1000; // 1 second between polls
this.previousState = new Map();
this.listeners = new Map();
this.isConnected = false;
this.pollTimer = null;
this.lastSync = 0;
this.isPolling = false;
this.options = {
logAllUpdates: options.logAllUpdates !== false,
filterMinorUpdates: options.filterMinorUpdates !== false,
...options,
};
}
start() {
console.log('[Polling] Starting...');
this.isConnected = true;
this._emit('connected');
this._poll();
}
async _poll() {
if (this.isPolling) return;
this.isPolling = true;
try {
const response = await fetch(
`${this.url}?lastSync=${this.lastSync}`,
{ signal: AbortSignal.timeout(35000) } // 35s timeout (30s + buffer)
);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const data = await response.json();
if (data.success) {
this.lastSync = data.timestamp;
if (data.updates.length > 0) {
console.log(`[Polling] Received ${data.updates.length} updates`);
data.updates.forEach((update) => {
this._processUpdate(update);
});
}
}
} catch (error) {
console.error('[Polling] Error:', error.message);
this._emit('error', error);
} finally {
this.isPolling = false;
// Schedule next poll
this.pollTimer = setTimeout(() => {
this._poll();
}, this.pollInterval);
}
}
_processUpdate(update) {
const { gameId, data: newGame } = update;
// Calculate delta
const delta = this._calculateDelta(gameId, newGame);
// Store new state
this.previousState.set(gameId, JSON.parse(JSON.stringify(newGame)));
// Detect event type from delta
const eventType = this._detectEventType(delta, newGame);
// Format notification
const notification = this._formatNotification(eventType, newGame, delta);
// Log and emit
this._logNotification(notification, eventType);
this._emit('update', {
type: eventType,
gameId,
game: newGame,
delta,
notification,
});
}
_calculateDelta(gameId, newGame) {
const oldGame = this.previousState.get(gameId);
const delta = {};
if (!oldGame) {
// First time seeing this game
delta.isNew = true;
return delta;
}
if (oldGame.homeTeam.score !== newGame.homeTeam.score) {
delta.homeScoreChange = newGame.homeTeam.score - oldGame.homeTeam.score;
}
if (oldGame.awayTeam.score !== newGame.awayTeam.score) {
delta.awayScoreChange = newGame.awayTeam.score - oldGame.awayTeam.score;
}
if (oldGame.status !== newGame.status) {
delta.statusChange = { from: oldGame.status, to: newGame.status };
}
if (oldGame.quarter !== newGame.quarter) {
delta.quarterChange = { from: oldGame.quarter, to: newGame.quarter };
}
if (oldGame.possession !== newGame.possession) {
delta.possessionChange = newGame.possession;
}
if (oldGame.time !== newGame.time) {
delta.timeChange = newGame.time;
}
return delta;
}
_detectEventType(delta, game) {
if (delta.homeScoreChange || delta.awayScoreChange) {
return 'score_update';
}
if (delta.statusChange?.to === 'finished') {
return 'game_finished';
}
if (delta.statusChange?.to === 'in_progress') {
return 'game_started';
}
if (delta.quarterChange) {
return 'quarter_change';
}
if (delta.possessionChange) {
return 'possession_change';
}
if (delta.timeChange) {
return 'time_update';
}
return 'game_update';
}
_formatNotification(type, game, delta) {
const timestamp = new Date().toLocaleTimeString();
const gameLabel = `${game.homeTeam.name} vs ${game.awayTeam.name}`;
switch (type) {
case 'game_started':
return `🎬 ${gameLabel} - GAME STARTED (${timestamp})`;
case 'score_update': {
const team = delta.homeScoreChange
? game.homeTeam.name
: game.awayTeam.name;
const points = delta.homeScoreChange || delta.awayScoreChange;
return `🏀 GOAL! ${team} scores ${points}pts! ` +
`(${game.homeTeam.name} ${game.homeTeam.score} - ${game.awayTeam.score} ${game.awayTeam.name}) - ${timestamp}`;
}
case 'quarter_change':
return `📊 ${gameLabel} - ${delta.quarterChange.to === 5 ? 'OT' : `Q${delta.quarterChange.to}`} (${timestamp})`;
case 'game_finished':
return `🏁 ${gameLabel} - FINAL: ${game.homeTeam.score} - ${game.awayTeam.score} (${timestamp})`;
case 'time_update':
return `⏱️ ${gameLabel} - ${game.time} in Q${game.quarter} (${timestamp})`;
default:
return `📢 ${gameLabel} (${timestamp})`;
}
}
_logNotification(message, type) {
const colors = {
score_update: '\x1b[33m%s\x1b[0m',
game_started: '\x1b[36m%s\x1b[0m',
quarter_change: '\x1b[35m%s\x1b[0m',
game_finished: '\x1b[32m%s\x1b[0m',
possession_change: '\x1b[34m%s\x1b[0m',
time_update: '\x1b[90m%s\x1b[0m',
};
const format = colors[type] || '%s';
console.log(format, message);
}
_emit(eventName, data) {
if (this.listeners.has(eventName)) {
this.listeners.get(eventName).forEach((callback) => {
callback(data);
});
}
}
on(eventName, callback) {
if (!this.listeners.has(eventName)) {
this.listeners.set(eventName, []);
}
this.listeners.get(eventName).push(callback);
}
off(eventName, callback) {
if (this.listeners.has(eventName)) {
const callbacks = this.listeners.get(eventName);
const index = callbacks.indexOf(callback);
if (index > -1) {
callbacks.splice(index, 1);
}
}
}
stop() {
console.log('[Polling] Stopping...');
this.isConnected = false;
if (this.pollTimer) {
clearTimeout(this.pollTimer);
this.pollTimer = null;
}
}
getGameState(gameId) {
return this.previousState.get(gameId);
}
getAllGames() {
const games = {};
this.previousState.forEach((game, gameId) => {
games[gameId] = game;
});
return games;
}
}
if (typeof module !== 'undefined' && module.exports) {
module.exports = SportsPollingClient;
}
4. HTML Dashboard
<!-- public/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Live Sports Scores Dashboard</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu,
Cantarell, sans-serif;
background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
color: #fff;
min-height: 100vh;
padding: 20px;
}
.container {
max-width: 1200px;
margin: 0 auto;
}
header {
margin-bottom: 30px;
text-align: center;
}
h1 {
font-size: 2.5em;
margin-bottom: 10px;
text-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
}
.controls {
display: flex;
gap: 10px;
justify-content: center;
flex-wrap: wrap;
margin: 20px 0;
}
button {
padding: 12px 24px;
font-size: 1em;
border: none;
border-radius: 5px;
cursor: pointer;
transition: all 0.3s ease;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.btn-primary {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
}
.btn-primary:hover:not(:disabled) {
transform: translateY(-2px);
box-shadow: 0 5px 20px rgba(102, 126, 234, 0.4);
}
.btn-primary:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.btn-secondary {
background: rgba(255, 255, 255, 0.2);
color: white;
border: 1px solid rgba(255, 255, 255, 0.3);
}
.btn-secondary:hover {
background: rgba(255, 255, 255, 0.3);
}
.status {
display: inline-block;
padding: 8px 16px;
border-radius: 20px;
font-size: 0.9em;
margin: 0 10px;
font-weight: 600;
}
.status.connected {
background: #4caf50;
color: white;
}
.status.disconnected {
background: #f44336;
color: white;
}
.status.polling {
background: #2196f3;
color: white;
}
.games-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
gap: 20px;
margin-bottom: 30px;
}
.game-card {
background: rgba(255, 255, 255, 0.1);
backdrop-filter: blur(10px);
border: 1px solid rgba(255, 255, 255, 0.2);
border-radius: 10px;
padding: 20px;
transition: all 0.3s ease;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}
.game-card:hover {
background: rgba(255, 255, 255, 0.15);
transform: translateY(-5px);
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.2);
}
.game-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 15px;
padding-bottom: 10px;
border-bottom: 1px solid rgba(255, 255, 255, 0.2);
}
.league-badge {
display: inline-block;
padding: 4px 12px;
background: rgba(102, 126, 234, 0.3);
border: 1px solid rgba(102, 126, 234, 0.5);
border-radius: 15px;
font-size: 0.85em;
font-weight: 600;
color: #a8b9ff;
}
.game-status {
font-size: 0.9em;
color: #b3b3b3;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.game-status.in_progress {
color: #4caf50;
}
.game-status.finished {
color: #ff9800;
}
.scoreboard {
display: flex;
justify-content: space-between;
align-items: center;
margin: 20px 0;
gap: 15px;
}
.team {
flex: 1;
text-align: center;
}
.team-name {
font-size: 1.2em;
font-weight: 600;
margin-bottom: 8px;
}
.team-score {
font-size: 3em;
font-weight: 700;
color: #a8b9ff;
line-height: 1;
}
.vs {
color: #999;
font-size: 0.9em;
margin: 0 10px;
}
.game-time {
text-align: center;
font-size: 1.3em;
font-weight: 600;
color: #ffd700;
margin: 15px 0;
}
.game-quarter {
text-align: center;
font-size: 0.9em;
color: #b3b3b3;
}
.game-details {
display: flex;
justify-content: space-between;
margin-top: 15px;
padding-top: 15px;
border-top: 1px solid rgba(255, 255, 255, 0.2);
font-size: 0.85em;
color: #b3b3b3;
}
.possession {
display: flex;
align-items: center;
gap: 5px;
}
.possession.home::before {
content: '🔵';
}
.possession.away::before {
content: '🔴';
}
.log-section {
background: rgba(0, 0, 0, 0.3);
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 10px;
padding: 20px;
max-height: 400px;
overflow-y: auto;
}
.log-title {
font-size: 1.2em;
font-weight: 600;
margin-bottom: 15px;
display: flex;
align-items: center;
gap: 10px;
}
.log-entry {
padding: 10px;
margin-bottom: 8px;
background: rgba(255, 255, 255, 0.05);
border-left: 3px solid #667eea;
border-radius: 3px;
font-size: 0.9em;
line-height: 1.5;
word-break: break-word;
}
.log-entry.score {
border-left-color: #ff9800;
background: rgba(255, 152, 0, 0.1);
}
.log-entry.status {
border-left-color: #4caf50;
background: rgba(76, 175, 80, 0.1);
}
.log-empty {
text-align: center;
color: #666;
padding: 20px;
font-style: italic;
}
.stats {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 15px;
margin-top: 30px;
}
.stat-card {
background: rgba(255, 255, 255, 0.05);
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 8px;
padding: 15px;
text-align: center;
}
.stat-value {
font-size: 2em;
font-weight: 700;
color: #a8b9ff;
}
.stat-label {
font-size: 0.85em;
color: #999;
text-transform: uppercase;
letter-spacing: 0.5px;
margin-top: 5px;
}
/* Scrollbar styling */
::-webkit-scrollbar {
width: 8px;
}
::-webkit-scrollbar-track {
background: rgba(255, 255, 255, 0.1);
border-radius: 10px;
}
::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.3);
border-radius: 10px;
}
::-webkit-scrollbar-thumb:hover {
background: rgba(255, 255, 255, 0.5);
}
@media (max-width: 768px) {
h1 {
font-size: 1.8em;
}
.games-grid {
grid-template-columns: 1fr;
}
.scoreboard {
flex-direction: column;
}
.team-score {
font-size: 2.5em;
}
}
.pulse {
animation: pulse 0.6s ease-in-out;
}
@keyframes pulse {
0%,
100% {
opacity: 1;
}
50% {
opacity: 0.7;
}
}
.mode-toggle {
text-align: center;
margin-top: 20px;
font-size: 0.9em;
}
.mode-indicator {
display: inline-block;
margin-left: 10px;
padding: 6px 12px;
background: rgba(255, 255, 255, 0.2);
border-radius: 15px;
font-weight: 600;
}
</style>
</head>
<body>
<div class="container">
<header>
<h1>🏆 Live Sports Dashboard</h1>
<p>Real-time game updates with delta changes</p>
</header>
<div class="controls">
<button class="btn-primary" id="sseBtn">Connect via SSE</button>
<button class="btn-primary" id="pollingBtn">Connect via Polling</button>
<button class="btn-secondary" id="disconnectBtn" style="display: none">
Disconnect
</button>
<span class="status disconnected" id="connectionStatus">Not Connected</span>
<span class="mode-indicator" id="modeIndicator" style="display: none"></span>
</div>
<div class="games-grid" id="gamesGrid"></div>
<div class="stats">
<div class="stat-card">
<div class="stat-value" id="totalUpdates">0</div>
<div class="stat-label">Updates Received</div>
</div>
<div class="stat-card">
<div class="stat-value" id="totalGames">0</div>
<div class="stat-label">Games Tracked</div>
</div>
<div class="stat-card">
<div class="stat-value" id="totalGoals">0</div>
<div class="stat-label">Scores</div>
</div>
<div class="stat-card">
<div class="stat-value" id="uptime">0s</div>
<div class="stat-label">Connected Time</div>
</div>
</div>
<div class="log-section">
<div class="log-title">📋 Event Log</div>
<div id="eventLog"></div>
</div>
</div>
<script src="sse-client.js"></script>
<script src="polling-client.js"></script>
<script>
// =====================================================
// DASHBOARD STATE
// =====================================================
let client = null;
let connectionMode = null;
const stats = {
updates: 0,
goals: 0,
startTime: null,
};
// =============================================
// EVENT LOG
// =============================================
const maxLogEntries = 50;
let logEntries = [];
function addLogEntry(message, type = 'default') {
logEntries.unshift({ message, type, timestamp: new Date() });
if (logEntries.length > maxLogEntries) {
logEntries.pop();
}
renderLog();
}
function renderLog() {
const logContainer = document.getElementById('eventLog');
if (logEntries.length === 0) {
logContainer.innerHTML = '<div class="log-empty">Waiting for updates...</div>';
return;
}
logContainer.innerHTML = logEntries
.map((entry) => {
let emoji = '📌';
if (entry.type === 'score') emoji = '🏀';
if (entry.type === 'status') emoji = '✅';
if (entry.type === 'error') emoji = '❌';
return `<div class="log-entry ${entry.type}">
${emoji} ${entry.message}
</div>`;
})
.join('');
}
// =============================================
// GAMES RENDERING
// =============================================
function renderGames() {
const gamesGrid = document.getElementById('gamesGrid');
const games = client.getAllGames();
if (Object.keys(games).length === 0) {
gamesGrid.innerHTML = '<div class="log-empty">No games data yet...</div>';
return;
}
gamesGrid.innerHTML = Object.entries(games)
.map(([gameId, game]) => renderGameCard(gameId, game))
.join('');
// Update stats
document.getElementById('totalGames').textContent = Object.keys(games).length;
}
function renderGameCard(gameId, game) {
const { homeTeam, awayTeam, status, quarter, time, possession, league } = game;
const statusClass = status.replace('_', '-');
const isFinished = status === 'finished';
const isInProgress = status === 'in_progress';
return `
<div class="game-card" id="game-${gameId}">
<div class="game-header">
<span class="league-badge">${league}</span>
<span class="game-status ${statusClass}">
${isFinished ? 'Final' : isInProgress ? 'Live' : 'Not Started'}
</span>
</div>
<div class="scoreboard">
<div class="team">
<div class="team-name">${homeTeam.name}</div>
<div class="team-score">${homeTeam.score}</div>
</div>
<div class="vs">vs</div>
<div class="team">
<div class="team-name">${awayTeam.name}</div>
<div class="team-score">${awayTeam.score}</div>
</div>
</div>
<div class="game-time">${time}</div>
<div class="game-quarter">
${isInProgress ? `Q${quarter}` : isFinished ? 'Final' : 'Not Started'}
</div>
<div class="game-details">
<div class="possession ${possession}">
${possession === 'home' ? homeTeam.name : awayTeam.name}
</div>
<div>⏱️ Updated: ${new Date(game.lastUpdate).toLocaleTimeString()}</div>
</div>
</div>
`;
}
// =============================================
// CONNECTION HANDLERS
// =============================================
document.getElementById('sseBtn').addEventListener('click', () => {
connectSSE();
});
document.getElementById('pollingBtn').addEventListener('click', () => {
connectPolling();
});
document.getElementById('disconnectBtn').addEventListener('click', () => {
disconnect();
});
function connectSSE() {
console.log('Connecting via SSE...');
connectionMode = 'SSE';
client = new SportsSSEClient({
url: '/api/sports/sse',
notificationSoundEnabled: false,
});
setupClientListeners();
client.connect();
}
function connectPolling() {
console.log('Connecting via Polling...');
connectionMode = 'Polling';
client = new SportsPollingClient({
url: '/api/sports/poll',
pollInterval: 1000,
});
setupClientListeners();
client.start();
}
function setupClientListeners() {
client.on('connected', () => {
console.log(`✅ Connected via ${connectionMode}`);
stats.startTime = Date.now();
updateConnectionStatus();
addLogEntry(`Connected via ${connectionMode}`, 'status');
startUptimeTimer();
});
client.on('disconnected', () => {
console.log(`❌ Disconnected from ${connectionMode}`);
updateConnectionStatus();
addLogEntry(`Disconnected from ${connectionMode}`, 'error');
});
client.on('error', (error) => {
console.error('Connection error:', error);
addLogEntry(`Error: ${error.message}`, 'error');
});
client.on('update', (update) => {
const { type, game, notification } = update;
console.log(`Update: ${type}`, update);
stats.updates++;
document.getElementById('totalUpdates').textContent = stats.updates;
if (type === 'score_update') {
stats.goals++;
document.getElementById('totalGoals').textContent = stats.goals;
addLogEntry(notification, 'score');
} else if (
type === 'game_started' ||
type === 'quarter_change' ||
type === 'game_finished'
) {
addLogEntry(notification, 'status');
} else {
addLogEntry(notification, 'default');
}
// Highlight updated game
const gameCard = document.getElementById(`game-${update.gameId}`);
if (gameCard && type !== 'time_update') {
gameCard.classList.add('pulse');
setTimeout(() => gameCard.classList.remove('pulse'), 600);
}
renderGames();
});
client.on('reconnect_failed', () => {
addLogEntry('Failed to reconnect after multiple attempts', 'error');
});
}
function disconnect() {
if (client) {
if (connectionMode === 'SSE') {
client.disconnect();
} else {
client.stop();
}
client = null;
connectionMode = null;
updateConnectionStatus();
logEntries = [];
renderLog();
}
}
function updateConnectionStatus() {
const statusEl = document.getElementById('connectionStatus');
const sseBtn = document.getElementById('sseBtn');
const pollingBtn = document.getElementById('pollingBtn');
const disconnectBtn = document.getElementById('disconnectBtn');
const modeIndicator = document.getElementById('modeIndicator');
if (client && connectionMode) {
statusEl.textContent = 'Connected';
statusEl.className = 'status connected';
sseBtn.disabled = true;
pollingBtn.disabled = true;
disconnectBtn.style.display = 'inline-block';
modeIndicator.style.display = 'inline-block';
modeIndicator.textContent = connectionMode;
} else {
statusEl.textContent = 'Not Connected';
statusEl.className = 'status disconnected';
sseBtn.disabled = false;
pollingBtn.disabled = false;
disconnectBtn.style.display = 'none';
modeIndicator.style.display = 'none';
}
}
let uptimeInterval = null;
function startUptimeTimer() {
if (uptimeInterval) clearInterval(uptimeInterval);
uptimeInterval = setInterval(() => {
if (stats.startTime) {
const elapsed = Math.floor((Date.now() - stats.startTime) / 1000);
document.getElementById('uptime').textContent = `${elapsed}s`;
}
}, 1000);
}
// =============================================
// INITIALIZATION
// =============================================
renderLog();
updateConnectionStatus();
window.addEventListener('beforeunload', () => {
if (client) disconnect();
});
</script>
</body>
</html>
5. Package.json & Setup
{
"name": "sports-live-scores",
"version": "1.0.0",
"description": "Live sports scores with SSE and long-polling",
"main": "server.js",
"scripts": {
"start": "node server.js",
"dev": "nodemon server.js",
"test": "jest"
},
"keywords": ["sports", "sse", "polling", "realtime"],
"author": "",
"license": "MIT",
"dependencies": {
"express": "^4.18.2",
"cors": "^2.8.5"
},
"devDependencies": {
"nodemon": "^3.0.1"
}
}
6. Usage & Testing
# Install dependencies
npm install
# Run server
npm start
# In browser, visit:
# http://localhost:3000
# Try both connection modes and watch the delta updates
Key Features:
✅ SSE (Server-Sent Events)
- Efficient one-way communication
- Automatic reconnection
- Lower latency updates
✅ Long-Polling
- Better browser compatibility
- Configurable polling interval
- Graceful timeout handling
✅ Delta Updates
- Tracks previous game state
- Only broadcasts significant changes
- Reduces console noise by 80%+
✅ Smart Event Filtering
- Minimal time updates (configurable)
- Highlights important events (goals, quarters)
- Color-coded log entries
✅ Production Ready
- Error handling & reconnection logic
- Performance monitoring (stats dashboard)
- Memory efficient state management
- Browser compatibility
The system efficiently tracks changes and only notifies on meaningful updates!