-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
44 lines (36 loc) · 1.14 KB
/
server.js
File metadata and controls
44 lines (36 loc) · 1.14 KB
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
// simple-chat/server.js
import express from 'express';
import http from 'http';
import { Server } from 'socket.io';
//=== Basic server ===
const app = express();
const server = http.createServer(app);
const io = new Server(server, { /* options (e.g., cors) can be added here */ });
// Serve the single static HTML page
app.get('/', (_req, res) => {
res.sendFile(`${process.cwd()}/index.html`);
});
// In‑memory chat history (last 100 messages)
const history = [];
//=== Socket.IO events ===
io.on('connection', socket => {
console.log(`User connected: ${socket.id}`);
// Send existing history
socket.emit('history', history);
// Broadcast new messages
socket.on('message', msg => {
const data = {
id: Date.now(),
user: socket.id,
text: msg,
time: new Date().toISOString()
};
history.push(data);
if (history.length > 100) history.shift(); // keep size
io.emit('message', data);
});
socket.on('disconnect', () => console.log(`Disconnected: ${socket.id}`));
});
//=== Start ===
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => console.log(`❶ Running on http://localhost:${PORT}`));