-
Notifications
You must be signed in to change notification settings - Fork 1
/
socket-server.js
57 lines (46 loc) · 1.18 KB
/
socket-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
var server = require('http').createServer()
, url = require('url')
, WebSocketServer = require('ws').Server
, wss = new WebSocketServer({ server: server, path: "/casino" })
, express = require('express')
, app = express()
, port = 5000
, cors = require('cors')
app.use(cors())
app.use(function (req, res) {
res.send({ msg: "hello" });
});
let clients = 0
wss.on('connection', function connection(ws) {
console.log('Connection')
clients++
ws.on('message', m => {
let msg = JSON.parse(m)
console.log('..', msg.type)
if (msg.type === `win`) {
wss.clients.forEach(client => {
client.send(JSON.stringify({
type: `gameover`,
}));
});
}
});
ws.on('close', function () {
console.log('Disconnection...')
clients--
wss.clients.forEach(client => {
client.send(JSON.stringify({
type: `newPlayer`,
numPlayers: clients,
}));
});
});
wss.clients.forEach(client => {
client.send(JSON.stringify({
type: `newPlayer`,
numPlayers: clients,
}));
});
});
server.on('request', app);
server.listen(port, function () { console.log('Listening on ' + server.address().port) });