2024-10-29 16:47:10 -04:00
|
|
|
import http from "http";
|
|
|
|
|
import { Server, ServerOptions } from "socket.io";
|
|
|
|
|
import { setupWebsocket } from "./socket/setupWebSocket";
|
2024-11-11 15:16:59 -05:00
|
|
|
import dotenv from "dotenv";
|
2024-11-26 17:04:22 -05:00
|
|
|
import express from "express";
|
|
|
|
|
import os from "os"; // Import the os module
|
2024-11-11 15:16:59 -05:00
|
|
|
|
|
|
|
|
// Load environment variables
|
|
|
|
|
dotenv.config();
|
2024-10-29 16:47:10 -04:00
|
|
|
|
2024-11-11 23:00:38 -05:00
|
|
|
const port = process.env.PORT || 4500;
|
|
|
|
|
const roomId = process.env.ROOM_ID;
|
2024-11-11 15:16:59 -05:00
|
|
|
console.log(`I am: /api/room/${roomId}/socket`);
|
2024-10-29 16:47:10 -04:00
|
|
|
|
2024-11-11 23:00:38 -05:00
|
|
|
// Create Express app for health check
|
|
|
|
|
const app = express();
|
|
|
|
|
const server = http.createServer(app);
|
|
|
|
|
|
|
|
|
|
// Health check endpoint
|
|
|
|
|
app.get('/health', (_, res) => {
|
|
|
|
|
try {
|
|
|
|
|
if (io.engine?.clientsCount !== undefined) {
|
|
|
|
|
res.status(200).json({
|
|
|
|
|
status: 'healthy',
|
|
|
|
|
path: `/api/room/${roomId}/socket`,
|
|
|
|
|
connections: io.engine.clientsCount,
|
|
|
|
|
uptime: process.uptime()
|
|
|
|
|
});
|
|
|
|
|
} else {
|
|
|
|
|
throw new Error('Socket.io server not initialized');
|
|
|
|
|
}
|
|
|
|
|
} catch (error: Error | any) {
|
|
|
|
|
res.status(500).json({
|
|
|
|
|
status: 'unhealthy',
|
|
|
|
|
error: error.message
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
2024-11-26 17:04:22 -05:00
|
|
|
|
2024-10-29 16:47:10 -04:00
|
|
|
const ioOptions: Partial<ServerOptions> = {
|
2024-11-11 23:00:38 -05:00
|
|
|
path: `/api/room/${roomId}/socket`,
|
2024-10-29 16:47:10 -04:00
|
|
|
cors: {
|
|
|
|
|
origin: "*",
|
|
|
|
|
methods: ["GET", "POST"],
|
|
|
|
|
credentials: true,
|
|
|
|
|
},
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const io = new Server(server, ioOptions);
|
|
|
|
|
|
|
|
|
|
// Initialize WebSocket setup
|
|
|
|
|
setupWebsocket(io);
|
|
|
|
|
|
|
|
|
|
server.listen(port, () => {
|
|
|
|
|
console.log(`WebSocket server is running on port ${port}`);
|
2024-11-26 17:04:22 -05:00
|
|
|
});
|