104 lines
2.9 KiB
JavaScript
104 lines
2.9 KiB
JavaScript
const express = require('express');
|
|
const WebSocket = require('ws');
|
|
const http = require('http');
|
|
const sqlite3 = require('sqlite3').verbose();
|
|
|
|
const app = express();
|
|
const server = http.createServer(app);
|
|
const wss = new WebSocket.Server({ server, path: '/counter-ws' });
|
|
|
|
// Initialize SQLite database
|
|
const db = new sqlite3.Database('./counter.db', (err) => {
|
|
if (err) {
|
|
console.error('Error opening database:', err.message);
|
|
} else {
|
|
console.log('Connected to SQLite database.');
|
|
// Create counter table if it doesn't exist
|
|
db.run(`CREATE TABLE IF NOT EXISTS counter (
|
|
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
value INTEGER DEFAULT 0
|
|
)`, (err) => {
|
|
if (err) {
|
|
console.error('Error creating table:', err.message);
|
|
} else {
|
|
// Initialize counter value if not exists
|
|
db.run(`INSERT OR IGNORE INTO counter (id, value) VALUES (1, 0)`, () => {
|
|
// Load initial counter value
|
|
loadCounterValue();
|
|
});
|
|
}
|
|
});
|
|
}
|
|
});
|
|
|
|
let counter = 0; // Will be loaded from database
|
|
|
|
// Function to load counter value from database
|
|
function loadCounterValue() {
|
|
db.get(`SELECT value FROM counter WHERE id = 1`, (err, row) => {
|
|
if (err) {
|
|
console.error('Error loading counter value:', err.message);
|
|
} else if (row) {
|
|
counter = row.value;
|
|
console.log('Loaded counter value:', counter);
|
|
}
|
|
});
|
|
}
|
|
|
|
app.use(express.json());
|
|
|
|
// API endpoint to get current counter value
|
|
app.get('/api/counter', (req, res) => {
|
|
res.json({ value: counter });
|
|
});
|
|
|
|
// API endpoint to increment counter
|
|
app.post('/api/counter/increment', (req, res) => {
|
|
counter += 1;
|
|
|
|
// Update counter value in database
|
|
db.run(`UPDATE counter SET value = ? WHERE id = 1`, [counter], (err) => {
|
|
if (err) {
|
|
console.error('Error updating counter in database:', err.message);
|
|
res.status(500).json({ error: 'Failed to update counter' });
|
|
return;
|
|
}
|
|
|
|
res.json({ value: counter });
|
|
|
|
// Broadcast update to all connected WebSocket clients
|
|
wss.clients.forEach(client => {
|
|
if (client.readyState === WebSocket.OPEN) {
|
|
client.send(JSON.stringify({ type: 'counter-update', value: counter }));
|
|
}
|
|
});
|
|
});
|
|
});
|
|
|
|
// WebSocket connection handling
|
|
wss.on('connection', (ws) => {
|
|
console.log('Client connected');
|
|
|
|
ws.on('message', (message) => {
|
|
const msg = Buffer.from(message).toString();
|
|
if (msg === '{"type":"ping"}') {
|
|
// Respond to ping to keep connection alive
|
|
ws.send(JSON.stringify({ type: 'pong' }));
|
|
} else {
|
|
console.log('Received:', msg);
|
|
}
|
|
});
|
|
|
|
ws.on('error', (error) => {
|
|
console.log('WebSocket error:', error);
|
|
});
|
|
|
|
ws.on('close', (code, reason) => {
|
|
console.log('Client disconnected', 'Code:', code, 'Reason:', reason.toString());
|
|
});
|
|
});
|
|
|
|
const PORT = 3001; // API and WebSocket server port
|
|
server.listen(PORT, '127.0.0.1', () => {
|
|
console.log(`Server running on http://127.0.0.1:${PORT}`);
|
|
}); |