-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex-ws.js
76 lines (62 loc) · 1.73 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
const express = require("express");
const server = require("http").createServer();
const app = express();
app.get("/", function(req, res) {
res.sendFile("index.html", {root: __dirname});
});
server.on("request", app);
server.listen(3000, function() {console.log("server started on port 3000")});
process.on('SIGINT', () => {
wss.clients.forEach(function each(client) {
client.close();
});
server.close(() => {
shutdownDB();
})
})
/** Begin Websocket */
const WebsocketServer = require("ws").Server;
const wss = new WebsocketServer({server: server});
wss.on("connection", function connection(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 close() {
const numClients = wss.clients.size;
wss.broadcast(`Current visitors: ${numClients}`);
console.log("Client has disconnected");
});
});
wss.broadcast = function broadcast(data) {
wss.clients.forEach(function each(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
)
`)
});
function getCounts() {
db.each("SELECT * FROM visitors", (err, row) => {
console.log(row);
})
}
function shutdownDB() {
getCounts();
console.log("Shutting Down DB");
db.close();
}