-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsocket.js
69 lines (59 loc) · 1.85 KB
/
socket.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
const EventEmmiter = require('events')
const WebSocket = require('ws')
const { v4: uuid } = require('uuid')
class WebSocketServer extends EventEmmiter {
constructor({ server }) {
super()
// we store our president vote here,
// its luber-jurdil we only save votes :)
this.presidents = {
jokawi: 0,
kobami: 0
}
// pass in your framework server object, so WebSocket will
// be using the port of your running server.
this.wss = new WebSocket.Server({ server })
// create emty object to store the socket, our user database
this.sockets = Object.create(null)
// ws is an websocket websockets
this.wss.on('connection', (ws, req) => {
let id = uuid() // generate random id
this.sockets[id] = ws // add user to the object
ws.on('message', message => {
// ws only accept strings that JSON,
// but you can send file too more on that later
try {
let msg = JSON.parse(message)
// emit here are from event emmiter
// we extends event emmiter on top remember
// docs on Node.js events https://nodejs.org/api/events.html
this.emit(msg.type, id, msg)
} catch (e) {
console.warn('invalid message', message)
console.error(e)
}
})
ws.on('close', () => {
delete this.sockets[id] // delete user if disconnected
})
// send user ID on connection
this.send(id, { type: "welcome", id: id, vote: this.presidents })
})
}
broadcast(msg) {
for (const key in this.sockets) {
this.send(key, msg)
}
}
send(id, msg) {
if (this.sockets[id]) {
this.sockets[id].send(JSON.stringify(msg));
} else {
console.warn(`no socket with the id ${id}`);
}
}
deleteId(id) {
delete this.sockets[id]
}
}
module.exports = WebSocketServer