-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
74 lines (51 loc) · 1.6 KB
/
index.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
const io= require("socket.io")(8800,{
cors:{
origin:"http://teamsbackendsocket:3000",
methods: [ "GET", "POST" ]
},
}
);
let users = [];
const addUser = (userId,socketId) =>{
!users.some(user=>user.userId ===userId) &&
users.push({userId,socketId});
};
const removeUser = (socketId) =>{
users =users.filter(user =>user.socketId !==socketId)
};
const getUser =(userId) =>{
return users.find(user=>user.userId === userId);
}
io.on("connection",(socket)=>{
//adding web rtc shit
socket.emit("me", socket.id);
socket.on("callUser", ({ userToCall, signalData, from, name }) => {
io.to(userToCall).emit("callUser", { signal: signalData, from, name });
});
socket.on("answerCall", (data) => {
io.to(data.to).emit("callAccepted", data.signal)
});
//when connect
console.log("a user connected.")
//take userId and socketId from user
socket.on("addUser",userId =>{
addUser(userId,socket.id);
io.emit("getUsers",users);
});
//send and get message
socket.on("sendMessage",({senderId,receiverId,text})=>{
const user = getUser(receiverId);
io.to(user.socketId).emit("getMessage",{
senderId,
text,
});
})
//when disconnect
socket.on("disconnect",() =>{
socket.broadcast.emit("callEnded")
console.log("for chat log : below");
console.log("a user disconnected");
removeUser(socket.id);
io.emit("getUsers",users);
});
});