Fix WebSocket, add auto refresh on frontend update

This commit is contained in:
2025-06-19 19:00:20 +02:00
parent e6dc59ee1b
commit 132578980c
6 changed files with 50 additions and 1018 deletions

20
ejs/footer.ejs Normal file
View File

@@ -0,0 +1,20 @@
<script>
let ws;
function connectWebSocket() {
const ws = new WebSocket((window.location.protocol === 'https:' ? 'wss://' : 'ws://') + window.location.host + window.location.pathname);
ws.onmessage = async (event) => {
if (event.data === 'update') {
location.reload();
}
};
ws.onclose = () => {
setTimeout(connectWebSocket, 5000);
};
}
connectWebSocket();
</script>

View File

@@ -53,4 +53,5 @@
<a href="/lobbies">Search Lobbies</a>
</div>
</body>
<%- include('footer') %>
</html>

View File

@@ -2,13 +2,34 @@ const express = require('express');
const path = require('path');
const { WebSocketServer } = require('ws');
const { createServer } = require('http');
const fs = require('fs');
const config = require('./config.json');
let clients = [];
const app = express();
const server = createServer(app);
const wss = new WebSocketServer({ server });
wss.on('connection', function connection(ws) {
clients.push(ws);
ws.on('close', () => {
clients.pop(ws);
});
});
// auto refresh on frontend update
let lastUpdateTime = Date.now();
fs.watch('./ejs/', () => {
const now = Date.now();
if (now - lastUpdateTime > 50) {
clients.forEach((ws) => {
ws.send('update');
});
}
lastUpdateTime = now;
});
app.use(express.json());
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'ejs'));
@@ -18,6 +39,6 @@ app.get('/', (req, res) => {
res.render('home');
});
app.listen(config.port, () => {
server.listen(config.port, () => {
console.log(`Server started on port ${config.port}`);
});

6
node_modules/.package-lock.json generated vendored
View File

@@ -412,6 +412,12 @@
"node": ">= 0.8"
}
},
"node_modules/fs": {
"version": "0.0.1-security",
"resolved": "https://registry.npmjs.org/fs/-/fs-0.0.1-security.tgz",
"integrity": "sha512-3XY9e1pP0CVEUCdj5BmfIZxRBTSDycnbqhIOGec9QYtmVH2fbLpj86CFWkrNOkt/Fvty4KZG5lTglL9j/gJ87w==",
"license": "ISC"
},
"node_modules/function-bind": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",

1017
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -2,6 +2,7 @@
"dependencies": {
"ejs": "^3.1.10",
"express": "^5.1.0",
"fs": "^0.0.1-security",
"ws": "^8.18.2"
}
}