-
Notifications
You must be signed in to change notification settings - Fork 6
/
socketEvents.js
42 lines (31 loc) · 1.07 KB
/
socketEvents.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
const socketEvents = (io) => {
let onlineUsers = {};
// Set socket.io listeners.
io.socket.on('connection', (socket) => {
// On conversation entry, join broadcast channel
socket.on('connected user', (data) => {
const socketId = socket.id;
const userId = data.id;
onlineUsers[userId] = data;
onlineUsers[userId].socketId = socketId;
io.socket.emit('new online', onlineUsers);
});
socket.on('disconnect', () => {
const socketId = socket.id;
let usersKey = Object.keys(onlineUsers)
usersKey.forEach((u) => {
if (onlineUsers[u].socketId === socketId) {
delete onlineUsers[u];
io.socket.emit('new online', onlineUsers);
}
})
});
socket.on('new message', (conversation) => {
// const receiverId = conversation.data.message.receiverId;
// console.log(onlineUsers[conversation.data.message.receiverId])
// const { socketId } = onlineUsers[receiverId];
io.socket.emit('message received', conversation);
});
});
};
module.exports = socketEvents;