-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsocket.js
More file actions
79 lines (65 loc) · 2.6 KB
/
socket.js
File metadata and controls
79 lines (65 loc) · 2.6 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
module.exports = (server) => {
let io = require('socket.io')(server);
/**
* 在线人员
*/
let onLineUsers = {};
/**
* 在线人数
*/
let onLineCounts = 0;
/**
* io监听到存在链接,此时回调一个socket进行socket监听
*/
io.on('connection', function (socket) {
console.log('a user connected');
/*监听新用户加入*/
socket.on('login', function (user) {
//暂存socket.name 为user.userId;在用户退出时候将会用到
socket.name = user.userId;
/*不存在则加入 */
if (!onLineUsers.hasOwnProperty(user.userId)) {
//不存在则加入
onLineUsers[user.userId] = user.userName;
onLineCounts++;
}
/**
* 一个用户新加入,向所有客户端监听login的socket的实例发送响应,响应内容为一个对象
*/
io.emit('login', {
onLineUsers: onLineUsers,
onLineCounts: onLineCounts,
user: user
});
console.log(user.userName, "加入了聊天室"); //在服务器控制台中打印么么么用户加入到了聊天室
});
/**
* 监听用户退出聊天室*
*/
socket.on('disconnect', function () {
if (onLineUsers.hasOwnProperty(socket.name)) {
let user = {
userId: socket.name,
userName: onLineUsers[socket.name]
};
delete onLineUsers[socket.name];
onLineCounts--;
/**
* 向所有客户端广播该用户退出群聊
*/
io.emit('logout', {
onLineUsers: onLineUsers,
onLineCounts: onLineCounts,
user: user
});
console.log(user.userName, "退出群聊");
}
})
/*监听到用户发送了消息,就使用io广播信息,信息被所有客户端接收并显示。注意,如果客户端自己发送的也会接收到这个消息,故在客户端应当存在这的判断,是否收到的消息是自己发送的,故在emit时,应该将用户的id和信息封装成一个对象进行广播*/
socket.on('message', function (obj) {
/*监听到有用户发消息,将该消息广播给所有客户端*/
io.emit('message', obj);
console.log(obj.userName, "说了:", obj.content);
});
});
}