-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
87 lines (73 loc) · 1.85 KB
/
server.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
const url = require('url')
//const https = require('https')
const http = require('http');
const fs = require('fs')
const WebSocket = require('ws')
let opts;
if(process.env.NODE_ENV === "production") {
opts = {
key: fs.readFileSync('/etc/nginx/gamechat.key'),
cert: fs.readFileSync('/etc/nginx/gamechat.crt')
}
}
else {
opts = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem'),
passphrase: 'password'
}
}
const server = http.createServer((req, res) => { res.end('hi') }).listen(4423)
//const server = https.createServer(opts, (req, res) => { res.end('hi') }).listen(8443);
const wss = new WebSocket.Server({ server })
const rooms = new Map(); // key: roomid, value: map of userid -> ws conn
wss.on('connection', (ws, req) => {
const location = url.parse(req.url, true)
console.log(location.query)
const connId = Math.random();
const roomId = location.query.id;
const userId = location.query.user;
if(rooms.has(roomId)) {
rooms.get(roomId)
.set(connId, {
userId,
ws
});
}
else {
const room = new Map();
room.set(connId, {
userId,
ws
});
rooms.set(roomId, room);
}
ws.on('message', msg => {
const { user, payload, target } = JSON.parse(msg);
const room = rooms.get(roomId);
// if theres no target, send to everyone except originating conn
if(!target || !target.id) {
room.forEach(userConn => {
if(userConn.ws !== ws) {
userConn.ws.send(msg)
}
})
}
else {
room.forEach(userConn => {
if(userConn.userId == target.id) {
userConn.ws.send(msg);
}
})
}
})
ws.on('close', () => {
console.log('closed', roomId, connId)
if(rooms.has(roomId)) {
rooms.get(roomId).delete(connId);
// for some reason ws connection keeps closing all the time.
// investigate that later
//rooms.get(roomId).forEach(c => c.send(JSON.stringify({ close: true })))
}
})
})