-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
55 lines (40 loc) · 1.38 KB
/
server.js
File metadata and controls
55 lines (40 loc) · 1.38 KB
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
const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const app = express();
app.use(express.json());
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
// Gestion des connexions WebSocket
wss.on('connection', (ws) => {
console.log('Client connected');
ws.on('message', (message) => {
console.log('Received:', message);
});
ws.on('close', () => {
console.log('Client disconnected');
});
});
const broadcastDeliveryUpdate = (event, delivery) => {
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({ event: event, delivery }));
}
});
};
app.post('/events/location_changed', (req, res) => {
const { delivery_id, location } = req.body;
const delivery = { delivery_id, location };
broadcastDeliveryUpdate("location_changed", delivery);
res.json({ message: 'Location updated', delivery });
});
app.post('/events/status_changed', (req, res) => {
const { delivery_id, status } = req.body;
const delivery = { delivery_id, status };
broadcastDeliveryUpdate("status_changed", delivery);
res.json({ message: 'Status updated', delivery });
});
const PORT = process.env.PORT || 3011;
server.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});