-
Notifications
You must be signed in to change notification settings - Fork 2
/
wsServer.js
79 lines (62 loc) · 1.76 KB
/
wsServer.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
var app = require('http').createServer()
var io = require('socket.io')(app)
var PORT = 3000
// 客户端计数
var clientCount = 0
// 用来存储客户端socket
var socketMap = {}
app.listen(PORT)
var bindListener = function(socket, event) {
socket.on(event, function (data) {
if(socket.clientNum % 2 == 0){
if(socketMap[socket.clientNum - 1]) {
socketMap[socket.clientNum - 1].emit(event, data)
}
}else {
if(socketMap[socket.clientNum + 1]) {
socketMap[socket.clientNum + 1].emit(event, data)
}
}
})
}
io.on('connection', function (socket) {
clientCount = clientCount + 1
socket.clientNum = clientCount
socketMap[clientCount] = socket
if(clientCount % 2 ==1){
socket.emit('waiting', 'waiting for another person')
} else {
if(socketMap[(clientCount - 1)]) {
socket.emit('start')
socketMap[(clientCount - 1)].emit('start')
}else {
socket.emit('leave')
}
}
bindListener(socket, 'init')
bindListener(socket, 'next')
bindListener(socket, 'rotate')
bindListener(socket, 'right')
bindListener(socket, 'down')
bindListener(socket, 'left')
bindListener(socket, 'fall')
bindListener(socket, 'fixed')
bindListener(socket, 'line')
bindListener(socket, 'time')
bindListener(socket, 'lose')
bindListener(socket, 'bottomLines')
bindListener(socket, 'addTailLines')
socket.on('disconnect', function () {
if(socket.clientNum % 2 == 0){
if(socketMap[socket.clientNum - 1]) {
socketMap[socket.clientNum - 1].emit('leave')
}
}else {
if(socketMap[socket.clientNum + 1]) {
socketMap[socket.clientNum + 1].emit('leave')
}
}
delete (socketMap[socket.clientNum])
})
})
console.log('websocket listening on port ' + PORT)