-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
84 lines (68 loc) · 2.03 KB
/
index.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
84
import { Server } from 'socket.io';
import { createServer} from 'node:http';
import express from 'express';
import {fileURLToPath} from 'node:url';
import {dirname, join} from 'node:path';
import sqlite3 from 'sqlite3';
import { open } from 'sqlite';
// open the database file
const db = await open({
filename: 'chat.db',
driver: sqlite3.Database
})
// create our 'messages' table
await db.exec(`
CREATE TABLE IF NOT EXISTS messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
client_offset TEXT UNIQUE,
content TEXT
);
`);
const app = express(); // create express app
const server = createServer(app); // create an http server
// create the socket.io server
const io = new Server(server, {
connectionStateRecovery: {}
})
const __dirname = dirname(fileURLToPath(import.meta.url));
app.get('/', (req, res) => {
res.sendFile(join(__dirname, 'index.html'));
})
io.on('connection', async (socket) => {
console.log('a user connected');
socket.on('chat message', async (msg) => {
let result;
try {
// store the message
result = await db.run('INSERT INTO messages (content) VALUES (?)', msg)
} catch (e) {
// handle the failure here
return;
}
console.log('message: ', msg, result.lastID);
io.emit('chat message', socket.username, msg, result.lastID);
})
socket.on("set username", (username) => {
socket.username = username;
console.log("Username set: ", username);
})
if(!socket.recovered) {
// if connection state recovering was not successful
try {
await db.each('SELECT id, content FROM messages WHERE id > ?',
[socket.handshake.auth.serverOffset || 0],
(_err, row) => {
socket.emit('chat message', row.content, row.id);
}
)
} catch (e){
// something went wrong
}
}
socket.on('disconnect', () => {
console.log('a user disconnected');
})
})
server.listen(3000, () => {
console.log('Server running on localhost:3000');
})