-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyServ.js
More file actions
112 lines (87 loc) · 3.35 KB
/
MyServ.js
File metadata and controls
112 lines (87 loc) · 3.35 KB
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
103
104
105
106
107
108
109
110
111
112
function MyServ(socket,roomList){
this.roomList = roomList;
this.socket = socket;
this.startTime= new Date().getTime()
this.heartBeatCount = 0;
this.isAdmin;
this.user;
this.init=() =>{
this.emitHeartBeat();
this.waitForGameStart();
this.roomLogic();
};
this.roomLogic= () => {
var that = this;
this.socket.on('join', function (roomID,user,isAdmin) {
that.user = user;
that.roomID = roomID;
that.isAdmin = isAdmin;
if (!that.roomList[roomID]) {
that.roomList[roomID] = {info:{
roomID:roomID,
gameStartTime:''
},adminSocket:'',user:[]};
}
if(isAdmin){
that.roomList[roomID].adminSocket = that.socket;
}
that.roomList[roomID].user.push(user);
that.socket.join(roomID);
if(that.roomList[roomID].adminSocket){
var adminSocket = that.roomList[roomID].adminSocket
adminSocket.emit('studentJoinRoom', user ,that.roomList[roomID].user);
}
that.socket.emit('gameInfo', that.roomList[roomID]['info']);
console.log(user + ' join ' + roomID);
});
this.socket.on('getRoomInfo', function () {
var room = that.roomList[that.roomID];
room.adminSocket.emit('RoomInfo', {
user:room.user,
info:room.info
});
});
this.socket.on('leave', function () {
that.socket.emit('disconnect');
});
this.socket.on('disconnect', function () {
if(!that.roomID){
return false;
}
var room = that.roomList[that.roomID];
var index = room.user.indexOf(that.user);
if (index !== -1) {
room.user.splice(index, 1);
}
that.socket.leave(that.roomID);
if(room.adminSocket){
room.adminSocket.emit('adminMsg', that.user + ' Quit',that.roomID);
}
console.log(that.user + '退出了' + that.roomID);
});
}
this.emitHeartBeat= () => {
setInterval(function(){
var timeStamp = new Date().getTime();
var duration = timeStamp -this.startTime;
this.socket.emit('HeartBeat', {
timeStamp:timeStamp,
duration : duration,
heartBeatCount : this.heartBeatCount++
});
}.bind(this), 1000);
}
this.waitForGameStart=()=>{
var that = this;
this.socket.on('gameStart', function () {
var room = that.roomList[that.roomID];
var gameStartTime = new Date().getTime();
room.info.gameStartTime = gameStartTime;
that.socket.to(that.roomID).emit('gameStart',
{
gameStartTime:gameStartTime
});
});
}
}
module.exports = MyServ;