forked from tianxiangbing/rooms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroom.js
50 lines (49 loc) · 1.5 KB
/
room.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
/**
* 房间
*/
const { MSG, actionType } = require('./message');
class Room {
constructor(roomId, user, io) {
this.peoples = [];
this.io = io;
this.roomId = roomId;
}
sendMsg(msg) {
msg.roomId = this.roomId;
console.log(`向${this.roomId}房间发送消息${msg}`)
this.io.to(this.roomId).emit('message', msg);
}
add(user, client) {
let roomId = this.roomId;
client.join(roomId, (a, b) => {
let rooms = Object.keys(client.rooms);
console.log(rooms);
user.updateRoom(roomId, client)
this.peoples.push(user);
console.log(`新的用户${user.uid}加入房间${roomId}`)
//发送固定的消息格式
this.sendMsg(new MSG(actionType.join, {
user: user.uid,
peoples: this.mapPeoples()
}));
})
}
mapPeoples() {
return this.peoples.map(user => user.info)
}
leave(user) {
this.peoples.forEach((item, index) => {
if (user.uid === item.uid) {
this.peoples.splice(index, 1);
user.client.leave(user.roomId, () => {
console.log(`${user.uid}离开了${user.roomId}号房间`)
this.sendMsg(new MSG(actionType.leave, {
user: user.uid,
peoples: this.mapPeoples()
}))
})
}
})
}
}
module.exports = Room;