-
Notifications
You must be signed in to change notification settings - Fork 0
/
socketServer.js
85 lines (69 loc) · 2.01 KB
/
socketServer.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
75
76
77
78
79
80
81
82
83
84
85
const { Server } = require("socket.io");
const socketServer = (server, port) => {
const io = new Server(server, {
cors: {
origin: "*",
},
});
console.log(`Server started on port ${port}`);
const users = [];
const chat = [];
let entryArray = [];
let loaderArray = [];
io.on("connection", (socket) => {
console.log("socket connect successful");
socket.on("newConnect", () => {
users.push(socket.id);
io.to(socket.id).emit("currentId", socket.id);
users.length < 2 ? io.to(socket.id).emit("videoData") : socket.broadcast.emit("echo");
});
socket.on("requestChat", () => {
socket.emit("updateChat", chat);
})
socket.on("newJoined", (videoObject) => {
entryArray.push({ user: socket.id, videoData: videoObject });
if (entryArray.length === users.length - 1) {
const missingUser = users.find(
(el) => !entryArray.some((obj) => obj.user === el)
);
io.to(missingUser).emit('videoData', entryArray[0].videoData);
entryArray = [];
}
});
socket.on("newIsReady", () => {
io.emit("avengersAssemble");
});
socket.on("videoVariant", (videoObject) => {
io.emit("newVideo", {
video: videoObject.video,
poster: videoObject.poster,
time: videoObject.time,
});
});
socket.on("play", () => {
io.emit("playConfirm");
});
socket.on("pause", () => {
io.emit("pauseConfirm");
});
socket.on("sendMessage", (message) => {
chat.push({ message: message, id: socket.id });
io.emit("updateChat", chat);
});
socket.on("ping", () => {
loaderArray.push(socket.id);
if (loaderArray.length === users.length) {
io.emit("pong");
loaderArray = [];
}
});
socket.on("disconnect", () => {
const index = users.indexOf(socket.id);
if (index !== -1) {
users.splice(index, 1);
}
console.log(`now users are ${users}`);
});
});
};
module.exports = socketServer;