From 4bd1daed40dd1e53eef8e644171f0397cb5ac6a1 Mon Sep 17 00:00:00 2001 From: Eyuep Sueyruege Date: Tue, 14 Nov 2023 16:56:48 +0100 Subject: [PATCH] Add test_examples/server.js --- test_examples/server.js | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 test_examples/server.js diff --git a/test_examples/server.js b/test_examples/server.js new file mode 100644 index 0000000..0844326 --- /dev/null +++ b/test_examples/server.js @@ -0,0 +1,38 @@ +const http = require('http'); +const WebSocket = require('ws'); + +// Erstelle einen HTTP-Server +const server = http.createServer((req, res) => { + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.end('WebSocket Server is running'); +}); + +// Erstelle einen WebSocket-Server, der an den HTTP-Server gebunden ist +const wss = new WebSocket.Server({ server }); + +// Event-Handler für eingehende WebSocket-Verbindungen +wss.on('connection', (ws) => { + console.log('Client connected'); + + // Event-Handler für eingehende Nachrichten vom Client + ws.on('message', (message) => { + client.send(`${message}`); + + // Sende die empfangene Nachricht an alle verbundenen Clients + wss.clients.forEach((client) => { + if (client !== ws && client.readyState === WebSocket.OPEN) { + client.send(message); + } + }); + }); + + // Event-Handler für das Schließen der WebSocket-Verbindung + ws.on('close', () => { + console.log('Client disconnected'); + }); +}); + +// Starte den Server auf Port 3000 +server.listen(3000, () => { + console.log('Server listening on http://localhost:3000'); +});