Displaying location info from websocket
This commit is contained in:
@@ -1,6 +1,11 @@
|
||||
import { broadcast } from './ws.js';
|
||||
|
||||
const handlers = {
|
||||
updateLocation(req, res) {
|
||||
console.log("req received")
|
||||
const { name, latitude, longitude, timestamp } = req.body;
|
||||
console.log(`Received location: (${name}, ${latitude}, ${longitude}) at ${timestamp}`);
|
||||
broadcast("update-location", { name, latitude, longitude, timestamp });
|
||||
res.json({ success: true });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,15 +4,14 @@ import http from 'http'
|
||||
import chalk from 'chalk'
|
||||
import moment from 'moment'
|
||||
import path from 'path';
|
||||
import httpProxy from 'http-proxy';
|
||||
const proxy = httpProxy.createProxyServer({});
|
||||
import { fileURLToPath } from 'url';
|
||||
import { initWebSocket } from './ws.js'
|
||||
|
||||
import Database from "./db.js"
|
||||
import AuthHandler from './auth.js';
|
||||
import handlers from "./handlers.js";
|
||||
|
||||
// Get __dirname in ES6 environment
|
||||
import { fileURLToPath } from 'url';
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
@@ -130,6 +129,7 @@ class Server {
|
||||
app.use('/', router);
|
||||
|
||||
const server = http.createServer(app);
|
||||
initWebSocket(server);
|
||||
const PORT = 3008;
|
||||
server.listen(PORT, () => {
|
||||
console.log("\n")
|
||||
|
||||
31
server/ws.js
Normal file
31
server/ws.js
Normal file
@@ -0,0 +1,31 @@
|
||||
import { WebSocket, WebSocketServer } from 'ws';
|
||||
|
||||
let wss;
|
||||
|
||||
export function initWebSocket(server) {
|
||||
wss = new WebSocketServer({ server });
|
||||
|
||||
wss.on('connection', (ws, req) => {
|
||||
console.log('✅ New WebSocket client connected');
|
||||
|
||||
ws.on('close', () => {
|
||||
console.log('Client disconnected');
|
||||
});
|
||||
});
|
||||
|
||||
console.log('WebSocket server initialized');
|
||||
}
|
||||
|
||||
// Broadcast a message to all connected clients
|
||||
export function broadcast(reqType, data) {
|
||||
if (!wss) return;
|
||||
|
||||
const payload = typeof data === 'string' ? data : JSON.stringify(data);
|
||||
const message = `${reqType}|${payload}`;
|
||||
|
||||
wss.clients.forEach(client => {
|
||||
if (client.readyState === WebSocket.OPEN) {
|
||||
client.send(message);
|
||||
}
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user