//获取玩家区服数据 let mysqlcn = require('./mysqlcn.js'); let query = mysqlcn.query; let http = require('http'); var qs = require('querystring'); let express = require('express'); let router = express.Router(); const timeout = 5000; // 设置超时时间为 5000 毫秒(5 秒) let ser_list = { // shengtian:{ // time : 0, // data : {} // } } // 创建一个封装 http 请求的 Promise function fetchDataFromServer(options, data) { return new Promise((resolve, reject) => { const req = http.request(options, (res) => { let data = ''; res.on('data', (chunk) => { data += chunk; }); res.on('end', () => { resolve(data); }); }); req.on('error', (e) => { reject(e); }); req.write(data) req.end(); }); } // 创建一个超时的 Promise function timeoutPromise(ms) { return new Promise((_, reject) => { setTimeout(() => { reject(new Error('请求超时')); }, ms); }); } // 从多个 URL 获取数据,处理超时 async function fetchAllDataWithTimeout(args, vals, timeout) { if(vals.length <= 0){ return [] } const dataTable = new Array(); const timeoutPromiseInstance = timeoutPromise(timeout); try { // 使用 Promise.race 处理超时 for (let i = 0; i < vals.length; i++) { const url = vals[i]; let data2game = JSON.stringify({ "sid" : vals[i].id, "channel" : args.channel, "account" : args.account, }) let opt = { method: "POST", host: vals[i].ip, port: vals[i].port, path: "/check_server", headers: { "Content-Type": 'application/json', "Content-Length": Buffer.byteLength(data2game, "utf8") } }; dataTable[i] = { "server_id": vals[i].id, "server_name": vals[i].name, "state": 0, "ip": vals[i].ip, "port": vals[i].game, "create": false, } const fetchPromise = fetchDataFromServer(opt, data2game); try { // 使用 Promise.race 处理每个请求的超时 const result = await Promise.race([fetchPromise, timeoutPromiseInstance]); // console.log(result) if(result != "Not Found") { const obj = JSON.parse(result); if (obj.state == 0){ dataTable[i].state = obj.open? 1:0 dataTable[i].create = obj.create } } } catch(error) { // console.log(error); } } return dataTable; } catch (error) { console.error('Error:', error); throw error; // 重新抛出错误以便调用者处理 } } let query_func = function(args, data, res){ fetchAllDataWithTimeout(args, data, timeout) .then((dataTable) => { let returndata = JSON.stringify({ 'code': 0, 'msg': "", 'data': dataTable, }); res.send(returndata); }).catch((error) => { console.error('Error:', error); res.send(JSON.stringify({ 'code':'400','msg':'稍后请求'})); }); } let server_query_info = function(args,res){ args = args ? args : {} let channel = args.channel ? args.channel : "" const timestamp = Date.now(); console.log(args) if (ser_list[channel] && ser_list[channel].time > timestamp){ query_func(args, ser_list[channel].data, res) } else{ let sql = `SELECT * FROM list where channel = "${channel}"`; query(sql,function(qerr,vals,fields_){ if (qerr==null){ ser_list[channel] = { time:timestamp+60000, data:vals, } query_func(args, vals, res) } else{ console.log("打开mysql库中服务器列表失败"); try{ res.send(JSON.stringify({ 'code':'400','msg':'稍后请求'})); } catch(e){ console.error('Error:', error); } } }); } } router.post('/server_query_info', (req, res) => { // 解析请求体中的数据 server_query_info(req.body, res) }); module.exports = router;