-
Notifications
You must be signed in to change notification settings - Fork 0
/
index-ws.js
78 lines (63 loc) · 1.64 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
import express from 'express';
import { createServer } from 'http';
const app = express();
const server = createServer(app);
app.get('/', (req, res) => {
res.sendFile('index.html', { root: process.cwd() });
});
server.listen(3000, () => {
console.log('Server started on port 3000');
});
process.on('SIGINT', ()=> {
wss.clients.forEach(function each(client){
client.close();
});
server.close(()=>{
shutdownDB();
})
})
/* Begin websocket */
import { WebSocketServer } from 'ws';
const wss = new WebSocketServer({ server: server });
wss.on('connection', function connection(ws) {
const numClients = wss.clients.size;
console.log('Client connected', numClients);
wss.broadcast(`Current visitors: ${numClients}`);
if (ws.readyState === ws.OPEN){
ws.send('Welcome to my chat');
}
db.run(`INSERT INTO visitors (count, time)
VALUES (${numClients}, datetime('now'))
`);
ws.on('close', function close() {
console.log('Client has disconnected');
wss.broadcast(`Current visitors: ${numClients}`);
});
});
wss.broadcast = function broadcast(data) {
wss.clients.forEach(function each(client) {
client.send(data);
});
};
/**begin database **/
import sqlite3 from 'sqlite3';
const sqlite = sqlite3.verbose();
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();
}