-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebSocketServer.js
More file actions
50 lines (42 loc) · 1.43 KB
/
webSocketServer.js
File metadata and controls
50 lines (42 loc) · 1.43 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
45
46
47
48
49
50
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
// Almacenar las conexiones de los clientes
const clients = new Set();
wss.on('connection', (ws) => {
// Agregar nuevo cliente a la lista
clients.add(ws);
ws.on('message', (message) => {
// Enviar el mensaje a todos los clientes conectados
/**
* jsonMessage {
* Buffer: valor,
* data: [arr de bytes]
* }
*/
const jsonMessage = JSON.stringify(message)
/**se obtiene la data del obj json message, se convierte de bytes a string y ese string se convierte a json
* jsonData {
* type: string,
* name: string,
* data: string [solo para el type === "message"]
*/
const jsonData = JSON.parse(String.fromCharCode(...JSON.parse(jsonMessage).data))
if (jsonData.type === 'message' || jsonData.type === 'login' || jsonData.type === 'exit'){
broadcast(JSON.stringify(jsonData));
}else{
console.error(`Error: Invalid type "${jsonData.type}"`);
}
console.log(JSON.parse(String.fromCharCode(...JSON.parse(jsonMessage).data)));
});
ws.on('close', () => {
// Eliminar cliente de la lista cuando se desconecta
clients.delete(ws);
console.log('Client disconnected');
});
});
function broadcast(message, isBinary) {
// Enviar el mensaje a todos los clientes conectados
clients.forEach((client) => {
client.send(message, { binary: isBinary});
});
}