Files
doneit-web/socket-server.js
T
2024-06-12 15:20:07 +01:00

37 lines
2.2 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
const WebSocket = require('ws');
const server = new WebSocket.Server({ port: 8080 });
server.on('connection', socket => {
console.log('Client connected');
// Broadcast a message to all clients when a new client connects
server.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({ type: 'info', payload: 'New client connected' }));
}
});
// Echo back messages to the client
socket.on('message', message => {
console.log('Received:', message);
const parsedMessage = JSON.parse(message);
// Broadcast the message to all connected clients
server.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({ type: parsedMessage.type, payload: parsedMessage.payload }));
}
});
});
socket.on('close', () => {
console.log('Client disconnected');
});
socket.on('error', (error) => {
console.error('WebSocket error:', error);
});
});
console.log('WebSocket server is running on ws://localhost:8080');