File size: 2,249 Bytes
466436b
 
 
 
 
 
 
 
 
 
 
 
 
502af73
 
 
 
 
 
466436b
 
 
 
 
 
 
 
 
 
 
 
0101721
466436b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cccfc29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
466436b
 
 
 
 
 
 
 
 
 
502af73
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
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"}`);
});