node-ws/volume/server.js
2025-05-12 19:31:33 +02:00

70 lines
1.8 KiB
JavaScript

import http from 'http';
import { WebSocketServer } from 'ws';
import fs from 'fs';
import path from 'path';
import url from 'url';
// 1. HTTP-Server erstellen
const server = http.createServer((req, res) => {
const parsedUrl = url.parse(req.url);
let pathname = `./volume/public${parsedUrl.pathname}`;
fs.exists(pathname, function (exist) {
if (!exist) {
res.statusCode = 404;
res.end(`File ${pathname} not found!`);
return;
}
// Wenn Pfad ein Verzeichnis ist, dann index.html annehmen
if (fs.statSync(pathname).isDirectory()) {
pathname += '/index.html';
}
fs.readFile(pathname, function (err, data) {
if (err) {
res.statusCode = 500;
res.end(`Error getting the file: ${err}.`);
} else {
res.statusCode = 200;
res.end(data);
}
});
});
});
// 2. WebSocket-Server auf dem HTTP-Server starten und auf /ws beschränken
const wss = new WebSocketServer({ noServer: true });
server.on('upgrade', (req, socket, head) => {
const pathname = url.parse(req.url).pathname;
if (pathname === '/ws') {
wss.handleUpgrade(req, socket, head, (ws) => {
wss.emit('connection', ws, req);
});
} else {
socket.destroy();
}
});
// 3. WebSocket-Handler
wss.on('connection', (socket) => {
console.log('Client connected to /ws');
socket.on('message', (message) => {
console.log(`Received: ${message}`);
socket.send(`Server: ${message}`);
});
socket.on('close', () => {
console.log('Client disconnected');
});
});
const PORT = 8080;
server.listen(PORT, () => {
console.log(`HTTP and WebSocket server running on http://localhost:${PORT}`);
});