-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
76 lines (58 loc) · 1.86 KB
/
server.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
// Load required modules
const http = require("http"); // http server core module
const path = require("path");
const express = require("express"); // web framework external module
// Set process name
process.title = "networked-aframe-server";
// Get port or default to 8080
const port = process.env.PORT || 8080;
// Setup and configure Express http server.
const app = express();
app.use(express.static('public'));
// Start Express http server
const webServer = http.createServer(app);
const io = require("socket.io")(webServer);
const rooms = {};
io.on("connection", socket => {
console.log("user connected", socket.id);
let curRoom = null;
socket.on("joinRoom", data => {
const { room } = data;
if (!rooms[room]) {
rooms[room] = {
name: room,
occupants: {},
};
}
const joinedTime = Date.now();
rooms[room].occupants[socket.id] = joinedTime;
curRoom = room;
console.log(`${socket.id} joined room ${room}`);
socket.join(room);
socket.emit("connectSuccess", { joinedTime });
const occupants = rooms[room].occupants;
io.in(curRoom).emit("occupantsChanged", { occupants });
});
socket.on("send", data => {
io.to(data.to).emit("send", data);
});
socket.on("broadcast", data => {
socket.to(curRoom).broadcast.emit("broadcast", data);
});
socket.on("disconnect", () => {
console.log('disconnected: ', socket.id, curRoom);
if (rooms[curRoom]) {
console.log("user disconnected", socket.id);
delete rooms[curRoom].occupants[socket.id];
const occupants = rooms[curRoom].occupants;
socket.to(curRoom).broadcast.emit("occupantsChanged", { occupants });
if (occupants == {}) {
console.log("everybody left room");
delete rooms[curRoom];
}
}
});
});
webServer.listen(port, () => {
console.log("listening on http://localhost:" + port);
});