-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
68 lines (60 loc) · 2.19 KB
/
index.js
File metadata and controls
68 lines (60 loc) · 2.19 KB
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
var app = require("express")();
var http = require("http").createServer(app);
var ws = require("ws");
/**
* Set up HTTP and WebSocket server.
*/
wss = new ws.Server({ noServer: true });
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
var server = http.listen(process.env.PORT || 3000, () => {
console.log("listening on *:%s", process.env.PORT || 3000);
});
server.on("upgrade", function (request, socket, head) {
wss.handleUpgrade(request, socket, head, (socket) => {
wss.emit("connection", socket, request);
});
});
/**
* Configure WebSocket responses.
*/
// Whenever a new client connects, this function is called.
wss.on("connection", function (connection) {
console.log("New connection.");
connection.website = false;
connection.registered = false;
connection.on("open", function (data) {
connection.send("Please register by replying BELLBOY or WEBSITE.");
});
connection.on("message", function (data) {
console.log("Got message: " + data.toString());
var string = data.toString();
if (connection.registered === false) {
console.log("An unregistered device connected, and needs to register...");
// Set up as a bellboy or website:
if (string.toUpperCase().startsWith("BELLBOY")) {
console.log("A BELLBOY client registered.");
connection.registered = true;
connection.send("REGISTERED - BELLBOY");
} else if (string.toUpperCase().startsWith("WEBSITE")) {
console.log("A WEBSITE client registered.");
connection.registered = true;
connection.website = true; // Indicate that this is a website.
connection.send("REGISTERED - WEBSITE");
} else {
// If neither BELLBOY or WEBSITE is specified, send an error message back.
console.log("Incorrect first message, waiting for correct input.");
connection.send("Failed to register, please send BELLBOY or WEBSITE.");
}
} else {
// Forward messages to all websites if the message is from a bellboy.
wss.clients.forEach(function (c) {
// Forward message if connection is a website.
if (c.website === true) {
c.send(string);
}
});
}
});
});