-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsocketServer.js
More file actions
66 lines (60 loc) · 1.82 KB
/
socketServer.js
File metadata and controls
66 lines (60 loc) · 1.82 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
let onlineUsers = [];
export default function (socket, io) {
//user joins or opens the application
socket.on("join", (user) => {
socket.join(user);
//add joined user to online users
if (!onlineUsers.some((u) => u.userId === user)) {
onlineUsers.push({ userId: user, socketId: socket.id });
}
//send online users to frontend
io.emit("get-online-users", onlineUsers);
//send socket id
io.emit("setup socket", socket.id);
});
//socket disconnect
socket.on("disconnect", () => {
onlineUsers = onlineUsers.filter((user) => user.socketId !== socket.id);
io.emit("get-online-users", onlineUsers);
});
//join a conversation room
socket.on("join conversation", (conversation) => {
socket.join(conversation);
});
//send and receive message
socket.on("send message", (message) => {
let conversation = message.conversation;
if (!conversation.users) return;
conversation.users.forEach((user) => {
if (user._id === message.sender._id) return;
socket.in(user._id).emit("receive message", message);
});
});
//typing
socket.on("typing", (conversation) => {
socket.in(conversation).emit("typing", conversation);
});
socket.on("stop typing", (conversation) => {
socket.in(conversation).emit("stop typing");
});
//call
//---call user
socket.on("call user", (data) => {
let userId = data.userToCall;
let userSocketId = onlineUsers.find((user) => user.userId == userId);
io.to(userSocketId.socketId).emit("call user", {
signal: data.signal,
from: data.from,
name: data.name,
picture: data.picture,
});
});
//---answer call
socket.on("answer call", (data) => {
io.to(data.to).emit("call accepted", data.signal);
});
//---end call
socket.on("end call", (id) => {
io.to(id).emit("end call");
});
}