@User8743
real time traffic light codes are possible to run while the site is being used.
code examples:
const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
let threadColor = 'initialColor';
app.get('/api/thread-color', (req, res) => {
res.json({ color: threadColor });
});
wss.on('connection', (ws) => {
// Send initial color to the connected client
ws.send(JSON.stringify({ color: threadColor }));
// Handle messages from the client (if needed)
ws.on('message', (message) => {
// Handle incoming messages from clients
});
});
// Update thread color every minute for demonstration purposes
setInterval(() => {
threadColor = getNextColor();
// Broadcast the color change to all connected clients
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({ color: threadColor }));
}
});
}, 60000); // Update every minute
// Start the server
server.listen(3000, () => {
console.log('Server is running on port 3000');
});
function getNextColor() {
// Implement logic to determine the next color based on your requirements
// For demonstration, you can use a predefined set of colors
const colors = ['color1', 'color2', 'color3'];
const currentIndex = colors.indexOf(threadColor);
const nextIndex = (currentIndex + 1) % colors.length;
return colors[nextIndex];
}
and
// Client-side (JavaScript)
const socket = new WebSocket('ws://localhost:3000');
socket.onopen = (event) => {
console.log('WebSocket connection opened:', event);
};
socket.onmessage = (event) => {
const data = JSON.parse(event.data);
updateThreadColor(data.color);
};
socket.onclose = (event) => {
console.log('WebSocket connection closed:', event);
};
function updateThreadColor(color) {
// Implement logic to update the thread color on the client side
// This could involve changing the CSS class, background color, etc.
console.log('Thread color updated:', color);
}