This repository has been archived by the owner on Sep 18, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
69 lines (63 loc) · 2.02 KB
/
app.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
const express = require("express")
const app = express()
const server = require("http").createServer(app)
const io = require("socket.io")(server)
app.use(express.static("public"));
server.listen(process.env.PORT || 5000, _ => {
console.log("Listening on port " + (process.env.PORT || "5000"))
})
// Format:
// [
// // HostID = index
// {
// hostSocket: socket,
// audioUrl: string,
// clients: [
// socket,
// socket,
// ...
// ],
// }
// ]
let hosts = []
io.on("connection", socket => {
console.log("Connected: " + socket.id)
socket.on("isHost", yes => {
if (yes) {
console.log("Type: Host")
const hostId = hosts.length
socket.emit("id", hostId)
hosts.push({hostSocket: socket, audioUrl: "", clients: []})
socket.on("url", url => {
hosts[hostId].audioUrl = url
play(hostId)
})
socket.on("disconnect", _ => {
console.log("Host disconnected: " + socket.id)
hosts[hostId].hostSocket = false
})
} else {
console.log("Type: Client")
socket.on("selectedHost", hostId => {
hosts[hostId].clients.push(socket)
hosts[hostId].hostSocket.emit("clients", hosts[hostId].clients.length)
socket.emit("joined")
socket.on("disconnect", _ => {
console.log("Client disconnected: " + socket.id)
const index = hosts[hostId].clients.indexOf(socket);
if (index > -1) {
hosts[hostId].clients.splice(index, 1);
}
play(hostId)
})
})
}
})
})
function play(hostId) {
if (hosts[hostId].clients.length > 0) {
hosts[hostId].clients[0].emit("play", hosts[hostId].audioUrl)
} else {
hosts[hostId].hostSocket.emit("play", hosts[hostId].audioUrl)
}
}