99 lines
2.4 KiB
JavaScript
99 lines
2.4 KiB
JavaScript
// sse-server.js
|
|
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
|
|
|
|
// 🔄 Client speichern
|
|
clients.set(steamId, res)
|
|
|
|
// 🫀 Heartbeat alle 25s
|
|
res.write('retry: 2000\n\n') // optional: Client-Reconnect-Vorschlag
|
|
const interval = setInterval(() => {
|
|
res.write(`event: ping\n`)
|
|
res.write(`data: {}\n\n`)
|
|
}, 25000)
|
|
|
|
req.on('close', () => {
|
|
clearInterval(interval) // 💡 sonst läuft dein setInterval ewig
|
|
clients.delete(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(8090, () => {
|
|
console.log('✅ SSE-Server läuft auf Port 8090')
|
|
})
|