Spaces:
Sleeping
Sleeping
| 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]; | |
| } | |
| } | |
| }); | |
| }); |