40 lines
822 B
JavaScript
40 lines
822 B
JavaScript
import { WebSocketServer } from 'ws';
|
|
|
|
let wss = null;
|
|
|
|
// Inicializar WebSocket Server
|
|
export function initWebSocket(server) {
|
|
wss = new WebSocketServer({ server, path: '/ws' });
|
|
|
|
wss.on('connection', (ws) => {
|
|
console.log('Cliente WebSocket conectado');
|
|
|
|
ws.on('close', () => {
|
|
console.log('Cliente WebSocket desconectado');
|
|
});
|
|
|
|
ws.on('error', (error) => {
|
|
console.error('Error WebSocket:', error);
|
|
});
|
|
});
|
|
|
|
return wss;
|
|
}
|
|
|
|
// Broadcast a todos los clientes WebSocket
|
|
export function broadcast(data) {
|
|
if (!wss) return;
|
|
|
|
wss.clients.forEach((client) => {
|
|
if (client.readyState === 1) { // WebSocket.OPEN
|
|
client.send(JSON.stringify(data));
|
|
}
|
|
});
|
|
}
|
|
|
|
// Obtener instancia del WebSocket Server
|
|
export function getWebSocketServer() {
|
|
return wss;
|
|
}
|
|
|