-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
37 lines (31 loc) · 944 Bytes
/
Copy pathserver.js
File metadata and controls
37 lines (31 loc) · 944 Bytes
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
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
// Setup basic Express app
const app = express();
const server = http.createServer(app);
// Setup Socket.IO server
const io = new Server(server, {
cors: {
origin: '*', // Allow all origins (use cautiously in prod)
methods: ['GET', 'POST'],
}
});
// Handle socket connections
io.on('connection', (socket) => {
console.log('✅ A user connected:', socket.id);
// Handle incoming chat messages
socket.on('chat message', (msg) => {
console.log('💬 Received:', msg);
io.emit('chat message', "Hello " + msg); // broadcast to all clients
});
// Handle disconnection
socket.on('disconnect', () => {
console.log('❌ A user disconnected:', socket.id);
});
});
// Start the server
const PORT = 3000;
server.listen(PORT, () => {
console.log(`🚀 Server is running on http://localhost:${PORT}`);
});