-
Notifications
You must be signed in to change notification settings - Fork 0
/
sockets.js
91 lines (75 loc) · 2.67 KB
/
sockets.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import { Server } from 'socket.io';
export function attachSockets(httpServer) {
const io = new Server(httpServer, {
cors: {
origin: "*", // Allow cross-origin requests if needed
methods: ["GET", "POST"]
}
});
// Stats object to hold visits and other details
let stats = {
visitsToday: 0,
totalVisits: 0,
totalCountries: new Set(),
connectedClients: new Set(),
};
io.on('connection', (socket) => {
handleNewConnection(socket, stats);
// Handle receiving a chat message
socket.on('chatMessage', (message) => handleChatMessage(io, socket, message));
// Handle disconnect event
socket.on('disconnect', () => handleDisconnection(io, socket, stats));
// Handle socket errors
socket.on('error', (error) => handleError(socket, error));
});
// Reset daily visits at midnight using setInterval
setInterval(() => resetDailyVisits(stats), 24 * 60 * 60 * 1000);
return io;
}
function handleNewConnection(socket, stats) {
// Increment visit counts and track connected clients
stats.visitsToday++;
stats.totalVisits++;
stats.connectedClients.add(socket.id);
// Get country from headers, default to 'Unknown'
const country = socket.handshake.headers['x-country'] || 'Unknown';
stats.totalCountries.add(country);
// Log the new connection and broadcast stats
console.log(`New connection from ${country}. Total visits today: ${stats.visitsToday}`);
broadcastStats(socket.server, stats);
}
function handleChatMessage(io, socket, message) {
// Emit chat message to all connected clients
io.emit('chatMessage', {
user: socket.id,
message,
timestamp: new Date().toISOString(),
});
console.log(`Message from ${socket.id}: ${message}`);
}
function handleDisconnection(io, socket, stats) {
// Remove client from connected clients set on disconnect
stats.connectedClients.delete(socket.id);
console.log(`Client ${socket.id} disconnected.`);
broadcastStats(io, stats); // Update stats after disconnection
}
function handleError(socket, error) {
// Log socket errors
console.error(`Error from client ${socket.id}:`, error);
}
function broadcastStats(io, stats) {
// Emit updated stats to all connected clients
io.emit('stats', {
visitsToday: stats.visitsToday,
totalVisits: stats.totalVisits,
totalVisitors: stats.connectedClients.size,
totalCountries: stats.totalCountries.size,
countrySet: Array.from(stats.totalCountries), // Convert Set to Array for broadcasting
});
}
function resetDailyVisits(stats) {
// Reset daily visits count and log the reset
stats.visitsToday = 0;
console.log('Daily visits reset.');
// Optional: Persist totalVisits and totalCountries to a database
}