const http = require('http') const url = require('url') const clients = new Map() // HTTP-Server starten const server = http.createServer((req, res) => { const parsedUrl = url.parse(req.url, true) // CORS & SSE-Header res.setHeader('Access-Control-Allow-Origin', '*') res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS') res.setHeader('Access-Control-Allow-Headers', 'Content-Type') if (req.method === 'OPTIONS') { res.writeHead(204) res.end() return } // Verbindung zu einem Client (SSE) if (req.method === 'GET' && req.url.startsWith('/events')) { const steamId = parsedUrl.query.steamId if (!steamId) { res.writeHead(400) res.end('steamId fehlt') return } // SSE-Header res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive', }) res.write('\n') // Verbindung offen halten clients.set(steamId, res) //console.log(`[SSE] Verbunden: steamId=${steamId}`) req.on('close', () => { clients.delete(steamId) //console.log(`[SSE] Verbindung geschlossen: steamId=${steamId}`) }) return } // Nachricht senden (POST) if (req.method === 'POST' && req.url === '/send') { let body = '' req.on('data', chunk => body += chunk) req.on('end', () => { const message = JSON.parse(body) const isBroadcast = !Array.isArray(message.targetUserIds) const type = message.type || 'notification' let sentCount = 0 for (const [steamId, clientRes] of clients.entries()) { const shouldSend = isBroadcast || ( Array.isArray(message.targetUserIds) && message.targetUserIds.includes(steamId) ) if (shouldSend) { clientRes.write(`event: ${type}\n`) clientRes.write(`data: ${JSON.stringify(message)}\n\n`) sentCount++ } } //console.log(`[SSE] Nachricht vom Typ "${type}" an ${sentCount} Client(s) gesendet.`) res.writeHead(200) res.end('Nachricht gesendet.') }) return } // Unbekannte Route res.writeHead(404) res.end() }) server.listen(3001, () => { console.log('✅ SSE-Server läuft auf Port 3001') })