123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229 |
- //获取玩家区服数据
- let mysqlcn = require('./mysqlcn.js');
- let query = mysqlcn.query;
- let http = require('http');
- let qs = require('querystring');
- let express = require('express');
- const { JsonWebTokenError } = require('jsonwebtoken');
- let router = express.Router();
- const timeout = 5000; // 设置超时时间为 5000 毫秒(5 秒)
- let ser_list = {
- // shengtian:{
- // time : 0,
- // data : {}
- // }
- }
- let channel_list= {
- shengtian : "FKYBT"
- }
- function ret_func(errno, data){
- let content = {
- status:"success",
- info:"success",
- data:data
- }
- if (errno != 0) {
- content.status = "failure"
- content.info = "failure"
- content.data = []
- }
- return JSON.stringify(content)
- }
- // 创建一个封装 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 fetchAllDataWithTimeoutRole(args, vals, timeout) {
- if(vals.length <= 0){
- return []
- }
- const dataTable = new Array();
- const timeoutPromiseInstance = timeoutPromise(timeout);
- try {
- console.log(vals)
- // 使用 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_role",
- headers: {
- "Content-Type": 'application/json',
- "Content-Length": Buffer.byteLength(data2game, "utf8")
- }
- };
- 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.create){
- dataTable.push({
- "serverId": vals[i].id,
- "serverName": vals[i].name,
- "actor": obj.name,
- "level": obj.level,
- "roleId": obj.uid,
- "createTime": obj.createtime,
- })
- }
- }
- } catch(error) {
- // console.log(error);
- }
- }
-
- return dataTable;
- } catch (error) {
- console.error('Error:', error);
- throw error; // 重新抛出错误以便调用者处理
- }
- }
- let query_role_fun = function(args,data, res){
- fetchAllDataWithTimeoutRole(args, data, timeout)
- .then((dataTable) => {
- res.send(ret_func(0, dataTable));
- }).catch((error) => {
- console.error('Error:', error);
- res.send(ret_func(1));
- });
- }
- let server_role_info = function(args,res){
- args = args ? args : {}
- if (args.gameCode == null || args.uid == null) {
- res.send(ret_func(1))
- return
- }
- let channel = ""
- let account = args.uid
- let gameCode = args.gameCode
- for (const [key, value] of Object.entries(channel_list)) {
- console.log(key, value);
- if (gameCode == value){
- channel = key
- break;
- }
- }
- if (channel=="") {
- res.send(ret_func(1))
- return
- }
- let info = {
- channel : channel,
- account : account
- }
- channel = args.channel ? args.channel : ""
- const timestamp = Date.now();
- if (ser_list[channel] && ser_list[channel].time > timestamp){
- query_role_fun(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_role_fun(info, vals, res)
- }
- else{
- console.log("打开mysql库中服务器列表失败");
- try{
- res.send(ret_func(1));
- }
- catch(e){
- console.error('Error:', error);
- }
- }
- });
- }
- }
- let role_info = function(args,res){
- console.log("role_info 回调接收:%s", args);
- try {
- let receipt = qs.parse(args)
- server_role_info(receipt, res)
- } catch(e) {
- console.log(e)
- res.send(ret_func(1));
- return;
- }
- }
- router.get('/role_info', function(req, res) {
- let pos = req.url.indexOf('?')
- let str = req.url
- if (pos == -1) { //请求的url是否包含?包含返回-1,==-1为不包含
- console.log("role_info 回调接收未找到参数");
- res.send(ret_func(1));
- } else {
- let data = str.substring(pos+1, str.length)
- role_info(data, res)
- };
- req.on("error",function(err){
- console.log("error:%s",err);
- res.send(ret_func(1));
- });
- });
- module.exports = router;
|