-
Notifications
You must be signed in to change notification settings - Fork 0
/
server-ws.js
55 lines (45 loc) · 1.46 KB
/
server-ws.js
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
51
52
53
54
55
const ws = require('ws');
const http = require("http");
/**
*
* @param {ws.WebSocketServer} wss
*/
function onListening(wss) {
console.log(`[Teox] <WS> Listening \n[Teox] <WS> Port: ${wss.address()?.port || "Invalido"}`);
};
function onError(error) {
console.log(`[Teox] <WS> Error: ${error.name} - ${error.message}`);
};
function onClose() {
console.log(`[Teox] <WS> Closed`);
};
/**
*
* @param {ws.WebSocketServer} wss
* @param {ws.WebSocket} ws
* @param {http.IncomingMessage} req
*/
function onConnection(wss, ws, req) {
const ip = req.headers['x-forwarded-for']?.toString() || "Invalido";
console.log(`[Teox] <WS> Cliente Conectado IP: ${ip}`);
ws.on("message", (data, isBinary) => {
let Data = data.toString("utf-8");
let DataJ = JSON.parse(Data);
console.log(DataJ)
console.log(`[Teox] <WS> Clients: ${wss.clients.size}`);
wss.clients.forEach((client) => {
client.send(`New Client`)
});
}); ws.on('close', () => console.log(`[Teox] <WS> Cliente Desconectado`));
};
module.exports = (servidor) => {
const wss = new ws.WebSocketServer({
server: servidor
});
wss.on('connection', (ws, request) => onConnection(wss, ws, request));
wss.on('error', onError);
wss.on('listening', () => onListening(wss));
wss.on('close', onClose);
console.log(`[Teox] <WS> Servidor Iniciado`);
return wss;
}