Spaces:
Sleeping
Sleeping
File size: 1,062 Bytes
912c620 |
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 |
const WebSocket = require('ws');
const PORT = process.env.PORT || 8080;
const server = new WebSocket.Server({ port: PORT });
console.log(`WebSocket server running on ws://localhost:${PORT}`);
const rooms = {};
server.on('connection', socket => {
socket.on('message', msg => {
const data = JSON.parse(msg);
if (data.type === 'join') {
socket.roomId = data.room;
rooms[data.room] = rooms[data.room] || new Set();
rooms[data.room].add(socket);
}
if (data.type === 'sync') {
(rooms[socket.roomId] || []).forEach(client => {
if (client !== socket && client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(data));
}
});
}
});
socket.on('close', () => {
if (socket.roomId && rooms[socket.roomId]) {
rooms[socket.roomId].delete(socket);
if (rooms[socket.roomId].size === 0) {
delete rooms[socket.roomId];
}
}
});
}); |