Spaces:
Sleeping
Sleeping
| const express = require("express"); | |
| const { createServer } = require("http"); | |
| const { Server } = require("socket.io"); | |
| const cors = require("cors"); | |
| const dotenv = require("dotenv"); | |
| const path = require("path"); | |
| dotenv.config(); | |
| const app = express(); | |
| const httpServer = createServer(app); | |
| const io = new Server(httpServer, { | |
| cors: { | |
| origin: | |
| process.env.NODE_ENV === "production" | |
| ? process.env.CLIENT_URL || "http://localhost:5173" | |
| : true, // Allow all origins in development | |
| methods: ["GET", "POST"], | |
| credentials: true | |
| } | |
| }); | |
| const PORT = process.env.PORT || 3000; | |
| const HOST = process.env.HOST || "localhost"; | |
| // Middleware | |
| app.use(cors()); | |
| app.use(express.json()); | |
| // Serve static files from frontend build (for production) | |
| if (process.env.NODE_ENV === "production") { | |
| const frontendPath = path.join(__dirname, "../../../../app/dist"); | |
| app.use(express.static(frontendPath)); | |
| // Serve index.html for all routes (SPA support) | |
| app.get("*", (req: any, res: any, next: any) => { | |
| if (req.path.startsWith("/health") || req.path.startsWith("/socket.io")) { | |
| return next(); | |
| } | |
| res.sendFile(path.join(frontendPath, "index.html")); | |
| }); | |
| } | |
| // Health check endpoint | |
| app.get("/health", (_req: any, res: any) => { | |
| res.json({ status: "ok", timestamp: new Date().toISOString() }); | |
| }); | |
| // Socket.io connection handling | |
| io.on("connection", (socket: any) => { | |
| console.log(`New client connected: ${socket.id}`); | |
| // Echo test handler | |
| socket.on("echo", (data: any, callback: any) => { | |
| const timestamp = new Date().toISOString(); | |
| const responseMessage = `Hello from server! Received: "${data.message}" at ${timestamp}`; | |
| console.log(`[Echo] Client ${socket.id}: ${data.message}`); | |
| // Send response via callback | |
| if (callback && typeof callback === "function") { | |
| callback({ | |
| message: responseMessage, | |
| serverTime: timestamp, | |
| clientTime: data.timestamp | |
| }); | |
| } | |
| }); | |
| socket.on("disconnect", () => { | |
| console.log(`Client disconnected: ${socket.id}`); | |
| }); | |
| }); | |
| // Start server | |
| httpServer.listen(PORT, HOST, () => { | |
| console.log(`Server running on ${HOST}:${PORT}`); | |
| console.log(`Health check: http://${HOST}:${PORT}/health`); | |
| console.log(`Environment: ${process.env.NODE_ENV || "development"}`); | |
| }); | |