-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex-ws.js
80 lines (64 loc) · 1.63 KB
/
index-ws.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
const express = require("express");
const server = require("http").createServer();
const app = express();
app.get("/", function getRoot(req, res) {
res.sendFile("index.html", { root: __dirname });
});
server.on("request", app);
server.listen(3000, function serverListen() {
console.log("Server started on port 3000");
});
process.on("SIGINT", () => {
wss.clients.forEach((client) => {
client.close();
});
server.close(() => {
shutdownDB();
});
})
// Begin websocket
const WebSocketServer = require("ws").Server;
const wss = new WebSocketServer({ server: server });
wss.on("connection", function wsConnection(ws) {
const numClients = wss.clients.size;
console.log("Clients connected", numClients);
wss.broadcast(`Current visitors: ${numClients}`);
if (ws.readyState === ws.OPEN) {
ws.send("Welcome to my server");
}
db.run(`INSERT INTO visitors (count, time)
VALUES (${numClients}, datetime('now'))
`);
ws.on("close", function wsClose() {
console.log("A client has disconnected");
wss.broadcast(`Current visitors: ${numClients}`);
});
});
wss.broadcast = function broadcast(data) {
wss.clients.forEach((client) => {
client.send(data);
});
};
// End websockets
// Begin database
const sqlite = require('sqlite3');
const db = new sqlite.Database(':memory:');
db.serialize(() => {
db.run(`
CREATE TABLE visitors (
count INTEGER,
time TEXT
)
`)
});
const getCounts = () => {
db.each("SELECT * FROM visitors", (err,row) => {
console.log('row', row);
});
}
const shutdownDB = () => {
getCounts();
console.log("Shutting down db");
db.close();
}
// End database