Code cleanup and optimization - removed debug logs and comments
This commit is contained in:
141
server.js
141
server.js
@@ -9,6 +9,10 @@ const app = express();
|
||||
|
||||
const server = http.createServer(app);
|
||||
|
||||
let cachedPrices = null;
|
||||
let lastFetchTime = 0;
|
||||
const CACHE_DURATION = 30000;
|
||||
|
||||
const io = socketIo(server, {
|
||||
cors: {
|
||||
origin: process.env.CORS_ORIGIN || "*",
|
||||
@@ -34,63 +38,69 @@ app.get("/health", (req, res) => {
|
||||
|
||||
// ========== Socket.IO Logic ==========
|
||||
|
||||
// 用於追蹤連接的客戶端數量
|
||||
// Number of clients
|
||||
let connectedClients = 0;
|
||||
|
||||
// 當客戶端連接時觸發
|
||||
// Trigger when client connected
|
||||
io.on("connection", (socket) => {
|
||||
// 增加客戶端計數
|
||||
connectedClients++;
|
||||
|
||||
console.log(`✅ 客戶端已連接: ${socket.id}`);
|
||||
console.log(`📊 當前連接數: ${connectedClients}`);
|
||||
console.log(`✅ Client Connected: ${socket.id}`);
|
||||
console.log(`📊 Current Number of Clients: ${connectedClients}`);
|
||||
|
||||
// 向所有客戶端廣播當前連接數
|
||||
// Broadcast to all clients
|
||||
io.emit("clientCount", connectedClients);
|
||||
|
||||
// ========== 監聽客戶端事件 ==========
|
||||
// ========== Monitoring client side events ==========
|
||||
|
||||
// 當客戶端要求數據時
|
||||
// Request Data
|
||||
socket.on("requestData", async (dataType) => {
|
||||
console.log(`📤 數據請求: ${dataType}`);
|
||||
console.log(`📤 Request Data: ${dataType}`);
|
||||
const now = new Date();
|
||||
|
||||
try {
|
||||
let data;
|
||||
|
||||
if (dataType === "crypto") {
|
||||
// 從 CoinGecko API 獲取加密貨幣數據
|
||||
const response = await axios.get(
|
||||
"https://api.coingecko.com/api/v3/simple/price",
|
||||
{
|
||||
params: {
|
||||
// 要查詢的加密貨幣
|
||||
ids: "bitcoin,ethereum,cardano,solana,ripple",
|
||||
// 使用 USD 幣種
|
||||
vs_currencies: "usd",
|
||||
// 包含市值
|
||||
include_market_cap: true,
|
||||
// 包含24小時交易量
|
||||
include_24hr_vol: true,
|
||||
// 包含24小時漲跌幅
|
||||
include_24hr_change: true,
|
||||
},
|
||||
}
|
||||
);
|
||||
if (cachedPrices && now - lastFetchTime < CACHE_DURATION) {
|
||||
console.log("📦 Use caching data");
|
||||
data = cachedPrices;
|
||||
} else {
|
||||
// Get data from "CoinGecko API"
|
||||
const response = await axios.get(
|
||||
"https://api.coingecko.com/api/v3/simple/price",
|
||||
{
|
||||
params: {
|
||||
// list of crypto requested to be shown
|
||||
ids: "bitcoin,ethereum,cardano,solana,ripple",
|
||||
vs_currencies: "usd",
|
||||
include_market_cap: true,
|
||||
include_24hr_vol: true,
|
||||
include_24hr_change: true,
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
// 組織數據格式
|
||||
data = {
|
||||
type: "crypto",
|
||||
timestamp: new Date(),
|
||||
prices: response.data,
|
||||
};
|
||||
// Construct data format
|
||||
data = {
|
||||
type: "crypto",
|
||||
timestamp: new Date(),
|
||||
prices: response.data,
|
||||
};
|
||||
|
||||
// Update Caches
|
||||
cachedPrices = data;
|
||||
lastFetchTime = now;
|
||||
console.log("✅ Cached New Data");
|
||||
}
|
||||
}
|
||||
|
||||
// 發送數據給要求的客戶端
|
||||
// Emit data to client side
|
||||
socket.emit("data", data);
|
||||
console.log(`✅ 數據已發送給客戶端: ${socket.id}`);
|
||||
console.log(`✅ Data sent to client: ${socket.id}`);
|
||||
} catch (error) {
|
||||
console.error("❌ 獲取數據出錯:", error.message);
|
||||
// 發送錯誤信息給客戶端
|
||||
console.error("❌ Error on Getting Data:", error.message);
|
||||
// Emit Error message to client side
|
||||
socket.emit("error", {
|
||||
message: "Failed to fetch data",
|
||||
details: error.message,
|
||||
@@ -98,12 +108,19 @@ io.on("connection", (socket) => {
|
||||
}
|
||||
});
|
||||
|
||||
// ========== 定期推送數據 ==========
|
||||
// ========== Push Data by interval ==========
|
||||
|
||||
// 創建定時器,每5秒推送一次數據給該客戶端
|
||||
// Push every 5 seconds
|
||||
const dataInterval = setInterval(async () => {
|
||||
try {
|
||||
// 獲取最新的加密貨幣數據
|
||||
const now = new Date();
|
||||
|
||||
if (cachedPrices && now - lastFetchTime < CACHE_DURATION) {
|
||||
socket.emit("data", cachedPrices);
|
||||
console.log(`[${now.toISOString()}]📦 Push Cached Data`);
|
||||
return;
|
||||
}
|
||||
// Get latest data
|
||||
const response = await axios.get(
|
||||
"https://api.coingecko.com/api/v3/simple/price",
|
||||
{
|
||||
@@ -117,57 +134,59 @@ io.on("connection", (socket) => {
|
||||
}
|
||||
);
|
||||
|
||||
// 向該客戶端發送數據(實時更新)
|
||||
socket.emit("data", {
|
||||
const data = {
|
||||
type: "crypto",
|
||||
timestamp: new Date(),
|
||||
prices: response.data,
|
||||
});
|
||||
};
|
||||
|
||||
cachedPrices = data;
|
||||
lastFetchTime = now;
|
||||
|
||||
socket.emit("data", data);
|
||||
} catch (error) {
|
||||
console.error("❌ 定時推送出錯:", error.message);
|
||||
console.error("❌ Error on pushing:", error.message);
|
||||
}
|
||||
}, 5000); // 每5000毫秒(5秒)執行一次
|
||||
}, CACHE_DURATION); // run every 30 seconds
|
||||
|
||||
// ========== 客戶端斷開連接 ==========
|
||||
// ========== Client Disconnected ==========
|
||||
|
||||
// 當客戶端斷開連接時觸發
|
||||
// Trigger when client disconnected
|
||||
socket.on("disconnect", () => {
|
||||
connectedClients--;
|
||||
console.log(`❌ 客戶端已斷開: ${socket.id}`);
|
||||
console.log(`📊 當前連接數: ${connectedClients}`);
|
||||
console.log(`❌ Client Disconnected: ${socket.id}`);
|
||||
console.log(`📊 Current Number of Clients: ${connectedClients}`);
|
||||
|
||||
// 向所有客戶端廣播更新的連接數
|
||||
// Broadcast number of clients
|
||||
io.emit("clientCount", connectedClients);
|
||||
|
||||
// 清除該客戶端的定時器
|
||||
// Clear client's interval
|
||||
clearInterval(dataInterval);
|
||||
});
|
||||
});
|
||||
|
||||
// ========== 啟動服務器 ==========
|
||||
// ========== Start service ==========
|
||||
|
||||
// 從環境變數獲取端口,或使用默認5000
|
||||
const PORT = process.env.PORT || 5000;
|
||||
|
||||
// 啟動伺服器
|
||||
server.listen(PORT, () => {
|
||||
console.log("");
|
||||
console.log("═══════════════════════════════════════");
|
||||
console.log(`✅ 服務器運行在: http://localhost:${PORT}`);
|
||||
console.log("📡 WebSocket 已準備接收連接");
|
||||
console.log("🔗 CORS 來源:", process.env.CORS_ORIGIN || "*");
|
||||
console.log(`✅ Server running on: http://localhost:${PORT}`);
|
||||
console.log("📡 WebSocket ready to connect");
|
||||
console.log("🔗 CORS Source:", process.env.CORS_ORIGIN || "*");
|
||||
console.log("═══════════════════════════════════════");
|
||||
console.log("");
|
||||
});
|
||||
|
||||
// ========== 錯誤處理 ==========
|
||||
// ========== Error Handling ==========
|
||||
|
||||
// 處理未捕獲的異常
|
||||
// Exception Handling
|
||||
process.on("unhandledRejection", (err) => {
|
||||
console.error("❌ 未捕獲的異常:", err);
|
||||
console.error("❌ Exceptions:", err);
|
||||
});
|
||||
|
||||
process.on("uncaughtException", (err) => {
|
||||
console.error("❌ 未捕獲的異常:", err);
|
||||
console.error("❌ Exceptions:", err);
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user