-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
83 lines (73 loc) · 1.6 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
77
78
79
80
81
82
83
//Including Web server
var web = require("./server/web.js");
//Starting server on Port 8080
web.start(8080);
//Main logic
//
var socket;
//server needs to store whiteboards and content
var rooms = [];
//room id used to distinguish rooms
var roomIds = {};
function getRoom(roomId)
{
if (!(roomId in roomIds))
{
roomIds[roomId] = rooms.length;
rooms.push([]);
}
return rooms[roomIds[roomId]];
}
function sendRoom(roomId)
{
web.io.emit("servermessage", {
"room": roomId,
"command": "send_room",
"data": getRoom(roomId)
});
}
function draw(msg)
{
var room = getRoom(msg["room"]);
room.push(msg["data"]);
web.io.emit("servermessage", {
"room": msg["room"],
"command": "draw",
"data": msg["data"]
});
}
function clear(msg)
{
var room = getRoom(msg["room"]);
while (room.length) room.pop();
web.io.emit("servermessage", {
"room": msg["room"],
"command": "clear"
});
}
function join(msg)
{
console.log("Client wants to join " + msg["room"]);
sendRoom(msg["room"]);
}
function handleMessage(msg)
{
try
{
//check if message is valid
if (!("room" in msg &&
"command" in msg))
return;
if (msg["command"] == "draw") draw(msg);
if (msg["command"] == "join") join(msg);
if (msg["command"] == "clear") clear(msg);
}
catch (err)
{
console.log(err);
}
}
web.io.on('connection', function (socket) {
console.log((new Date()) + ' Connection established.');
socket.on("message", handleMessage);
});