-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
102 lines (77 loc) · 2.77 KB
/
index.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
// Importar las bibliotecas necesarias
const http = require('http');
const httpServer = http.createServer();
const path = require('path');
const { client } = require('websocket/lib/websocket');
const app = require("express")();
app.listen(9001, ()=>{
console.log("Escuchando en 9001");
})
/*app.get('/', (req, res) =>{
res.sendFile(path.join(__dirname, 'index.html'))
})*/
app.get('/', (req, res) =>{
res.sendFile(path.join(__dirname, 'index.html'))
})
const WebSocketServer = require('websocket/lib/WebSocketServer');
const websocket = require('websocket').server;
const clients = {};
const games = {};
const rooms = {};
const wsServer = new WebSocketServer({
"httpServer":httpServer
})
wsServer.on("request", req => {
const connection = req.accept(null, req.origin);
connection.on("open", () => console.log("opened!"))
connection.on("close", () => console.log("closed!"))
connection.on("message", message => {
const result = JSON.parse(message.utf8Data)
//Un usuario quiere entrar
if(result.method === "login"){
const clientID = result.clientID;
clients[clientID].nickname = result.nickname
//Información de nuevo conectado a todos los usuarios
wsServer.broadcast(JSON.stringify({
method: 'broadcast',
message: {'type':'newUser', 'nickname': result.nickname}
}))
///Mensaje al usuario conectado
connection.send(JSON.stringify({
method: 'communication',
message: {'type':'logged', 'value': 'in', 'clientID': clientID, 'nickname': result.nickname}
}))
} else if(result.method === "chatMessage"){
const clientID = result.clientID;
const nickname = clients[clientID].nickname;
const chatMessage = result.message
wsServer.broadcast(JSON.stringify({
method: 'broadcast',
message: {'type':'newChatMessage', 'clientID': clientID, 'nickname': nickname, 'message': chatMessage}
}))
}
})
const clientID = generateGUID();
clients[clientID] = {
"connection":connection,
"nickname" : null
}
const payLoad ={
"method" : "connect",
"clientID" : clientID
}
connection.send(JSON.stringify(payLoad));
})
function generateGUID() {
let guid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
const r = Math.random() * 16 | 0;
const v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
return guid;
}
// Iniciar el servidor
const PORT = 9000;
httpServer.listen(PORT, () => {
console.log(`Servidor iniciado en el puerto ${PORT}`);
});