Enhance Socket.IO integration and improve error handling
- Updated CORS configuration for Socket.IO to allow all origins and added specific allowed headers. - Improved error handling for Socket.IO connections, including detailed logging for connection errors and upgrade attempts. - Implemented cleanup logic for socket connections during page reloads to prevent stale connections. - Enhanced reconnection logic with unlimited attempts and improved logging for connection status. - Updated frontend socket service to manage club room joining and leaving more effectively, with better state handling. - Configured Vite for improved hot module replacement (HMR) settings to support local development.
This commit is contained in:
@@ -60,12 +60,14 @@ const port = process.env.PORT || 3005;
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
// CORS-Konfiguration - Socket.IO hat seine eigene CORS-Konfiguration
|
||||
app.use(cors({
|
||||
origin: true,
|
||||
credentials: true,
|
||||
methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
|
||||
allowedHeaders: ['Content-Type', 'Authorization', 'authcode', 'userid']
|
||||
}));
|
||||
|
||||
app.use(express.json());
|
||||
|
||||
// Request Logging Middleware - loggt alle API-Requests
|
||||
@@ -117,6 +119,11 @@ app.use('/api/training-times', trainingTimeRoutes);
|
||||
|
||||
// Middleware für dynamischen kanonischen Tag (vor express.static)
|
||||
const setCanonicalTag = (req, res, next) => {
|
||||
// Socket.IO-Requests komplett ignorieren
|
||||
if (req.path.startsWith('/socket.io/')) {
|
||||
return next();
|
||||
}
|
||||
|
||||
// Nur für HTML-Anfragen (nicht für API, Assets, etc.)
|
||||
if (req.path.startsWith('/api') || req.path.match(/\.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot|mp3|webmanifest|xml|txt)$/)) {
|
||||
return next();
|
||||
@@ -316,13 +323,13 @@ app.use((err, req, res, next) => {
|
||||
|
||||
// Erstelle HTTP-Server für API
|
||||
const httpServer = createServer(app);
|
||||
httpServer.listen(port, () => {
|
||||
console.log(`🚀 HTTP-Server läuft auf Port ${port}`);
|
||||
});
|
||||
|
||||
|
||||
// WICHTIG: Socket.IO muss VOR dem Server-Start initialisiert werden
|
||||
// damit es Upgrade-Requests abfangen kann
|
||||
let socketIOInitialized = false;
|
||||
|
||||
// Erstelle HTTPS-Server für Socket.IO (direkt mit SSL)
|
||||
const httpsPort = process.env.HTTPS_PORT || 3051;
|
||||
let socketIOInitialized = false;
|
||||
|
||||
// Prüfe, ob SSL-Zertifikate vorhanden sind
|
||||
const sslKeyPath = '/etc/letsencrypt/live/tt-tagebuch.de/privkey.pem';
|
||||
@@ -335,28 +342,51 @@ app.use((err, req, res, next) => {
|
||||
cert: fs.readFileSync(sslCertPath)
|
||||
};
|
||||
|
||||
// Erstelle HTTPS-Server mit Express-App
|
||||
const httpsServer = https.createServer(httpsOptions, app);
|
||||
|
||||
// Initialisiere Socket.IO auf HTTPS-Server
|
||||
// Initialisiere Socket.IO auf HTTPS-Server VOR dem Listen
|
||||
initializeSocketIO(httpsServer);
|
||||
socketIOInitialized = true;
|
||||
|
||||
httpsServer.listen(httpsPort, '0.0.0.0', () => {
|
||||
console.log(`🚀 HTTPS-Server für Socket.IO läuft auf Port ${httpsPort}`);
|
||||
console.log(` Socket.IO Endpoint: https://tt-tagebuch.de:${httpsPort}/socket.io/`);
|
||||
});
|
||||
|
||||
// Error-Handling für HTTPS-Server
|
||||
httpsServer.on('error', (err) => {
|
||||
console.error('❌ HTTPS-Server Error:', err.message);
|
||||
console.error(' Code:', err.code);
|
||||
});
|
||||
|
||||
httpsServer.on('clientError', (err, socket) => {
|
||||
if (socket && !socket.destroyed) {
|
||||
console.error('❌ HTTPS-Server Client Error:', err.message);
|
||||
socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
|
||||
}
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('⚠️ HTTPS-Server konnte nicht gestartet werden:', err.message);
|
||||
console.error(' Stack:', err.stack);
|
||||
console.log(' → Socket.IO läuft auf HTTP-Server (nur für Entwicklung)');
|
||||
}
|
||||
} else {
|
||||
console.log('ℹ️ SSL-Zertifikate nicht gefunden - Socket.IO läuft auf HTTP-Server (nur für Entwicklung)');
|
||||
console.log(` Erwartete Pfade: ${sslKeyPath}, ${sslCertPath}`);
|
||||
}
|
||||
|
||||
// Fallback: Socket.IO auf HTTP-Server (wenn noch nicht initialisiert)
|
||||
// WICHTIG: VOR dem httpServer.listen() initialisieren
|
||||
if (!socketIOInitialized) {
|
||||
initializeSocketIO(httpServer);
|
||||
console.log(' ✅ Socket.IO erfolgreich auf HTTP-Server initialisiert');
|
||||
}
|
||||
|
||||
// HTTP-Server starten NACH Socket.IO-Initialisierung
|
||||
httpServer.listen(port, () => {
|
||||
console.log(`🚀 HTTP-Server läuft auf Port ${port}`);
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Unable to synchronize the database:', err);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user