token AES 密钥生成加密,收藏rom功能和api

This commit is contained in:
sin365 2025-01-08 13:30:58 +08:00
parent 31da819ad0
commit 8b8a055cd1
31 changed files with 2354 additions and 611 deletions

View File

@ -46,7 +46,7 @@ namespace AxibugEmuOnline.Client.ClientCore
#else #else
public static string PersistentDataPath => Application.persistentDataPath; public static string PersistentDataPath => Application.persistentDataPath;
#endif #endif
public static void Init(bool isTest = false, string testSrvIP = "") public static void Init(bool isTest = false, string testSrvIP = "", bool bUseLocalWebApi = false, string mLocalWebApi = "")
{ {
log = new LogManager(OnLogOut); log = new LogManager(OnLogOut);
@ -64,6 +64,8 @@ namespace AxibugEmuOnline.Client.ClientCore
emu = new AppEmu(); emu = new AppEmu();
//netgame = new AppNetGame(); //netgame = new AppNetGame();
httpAPI = new HttpAPI(); httpAPI = new HttpAPI();
if (bUseLocalWebApi)
httpAPI.WebHost = mLocalWebApi;
nesRomLib = new RomLib(RomPlatformType.Nes); nesRomLib = new RomLib(RomPlatformType.Nes);
CacheMgr = new CacheManager(); CacheMgr = new CacheManager();
roomMgr = new AppRoom(); roomMgr = new AppRoom();

View File

@ -170,7 +170,14 @@ public static class AxiHttp
if (!dictIP2Address.ContainsKey(str)) if (!dictIP2Address.ContainsKey(str))
{ {
IPHostEntry host = Dns.GetHostEntry(str); IPHostEntry host = Dns.GetHostEntry(str);
IPAddress ip = host.AddressList[0]; IPAddress ip = null;
foreach (var item in host.AddressList)
{
if (item.AddressFamily == AddressFamily.InterNetwork)
{
ip = item; break;
}
}
dictIP2Address[str] = ip; dictIP2Address[str] = ip;
} }
return dictIP2Address[str]; return dictIP2Address[str];

View File

@ -17,15 +17,17 @@ namespace AxibugEmuOnline.Client
#if UNITY_EDITOR #if UNITY_EDITOR
public bool bTest = false; public bool bTestSkipWebApiToConServer = false;
public string mTestSrvIP = "192.168.0.47"; public string mTestSrvIP = "192.168.0.47";
public bool bUseLocalWebApi = false;
public string mLocalWebApi = "http://localhost:5051";
public bool bEditorUUID = false; public bool bEditorUUID = false;
#endif #endif
private void Awake() private void Awake()
{ {
#if UNITY_EDITOR #if UNITY_EDITOR
App.Init(bTest, mTestSrvIP); App.Init(bTestSkipWebApiToConServer, mTestSrvIP, bUseLocalWebApi,mLocalWebApi);
dev_UUID = SystemInfo.deviceUniqueIdentifier; dev_UUID = SystemInfo.deviceUniqueIdentifier;
if (bEditorUUID) if (bEditorUUID)
{ {

View File

@ -73,7 +73,7 @@ namespace AxibugEmuOnline.Client.Manager
if (msg.Status == LoginResultStatus.Ok) if (msg.Status == LoginResultStatus.Ok)
{ {
App.log.Info("登录成功"); App.log.Info("登录成功");
App.user.InitMainUserData(App.user.userdata.Account, msg.UID); App.user.InitMainUserData(App.user.userdata.Account, msg.UID, msg.Token);
OverlayManager.PopTip("登录成功"); OverlayManager.PopTip("登录成功");

View File

@ -17,12 +17,12 @@ namespace AxibugEmuOnline.Client.Manager
/// 发送收藏 /// 发送收藏
/// </summary> /// </summary>
/// <param name="RomID"></param> /// <param name="RomID"></param>
/// <param name="Motion">[0]收藏[1]取消收藏</param> /// <param name="Motion">[0]取消收藏[1]收藏</param>
public void SendGameStar(int RomID, int Motion) public void SendGameStar(int RomID, int Motion)
{ {
Protobuf_Game_Mark req = new Protobuf_Game_Mark() Protobuf_Game_Mark req = new Protobuf_Game_Mark()
{ {
State = Motion, Motion = Motion,
RomID = RomID, RomID = RomID,
}; };
App.log.Info($"LeavnRoom"); App.log.Info($"LeavnRoom");

View File

@ -14,16 +14,15 @@ namespace AxibugEmuOnline.Client
public delegate void GetRomListAPI(Action<int, Resp_GameList> callback, AxibugProtobuf.RomPlatformType Platform, int page, int pageSize = 10); public delegate void GetRomListAPI(Action<int, Resp_GameList> callback, AxibugProtobuf.RomPlatformType Platform, int page, int pageSize = 10);
public delegate void SearchRomListAPI(Action<int, Resp_GameList> callback, AxibugProtobuf.RomPlatformType Platform, string searchKey, int page, int pageSize = 10); public delegate void SearchRomListAPI(Action<int, Resp_GameList> callback, AxibugProtobuf.RomPlatformType Platform, string searchKey, int page, int pageSize = 10);
public void GetNesRomList(Action<int, Resp_GameList> callback, AxibugProtobuf.RomPlatformType platform, int page, int pageSize = 10) public void GetRomList(Action<int, Resp_GameList> callback, AxibugProtobuf.RomPlatformType platform, int page, int pageSize = 10)
{ {
App.StartCoroutine(GetRomListFlow(platform, page, pageSize, callback)); App.StartCoroutine(GetRomListFlow(platform, page, pageSize, callback));
} }
public void SearchRomList(Action<int, Resp_GameList> callback, AxibugProtobuf.RomPlatformType platform, string searchKey, int page, int pageSize = 10)
public void SearchNesRomList(Action<int, Resp_GameList> callback, AxibugProtobuf.RomPlatformType platform, string searchKey, int page, int pageSize = 10)
{ {
App.StartCoroutine(SearchNesRomListFlow(platform, searchKey, page, pageSize, callback)); App.StartCoroutine(SearchRomListFlow(platform, searchKey, page, pageSize, callback));
} }
private IEnumerator SearchNesRomListFlow(AxibugProtobuf.RomPlatformType platform, string searchKey, int page, int pageSize, Action<int, Resp_GameList> callback) private IEnumerator SearchRomListFlow(AxibugProtobuf.RomPlatformType platform, string searchKey, int page, int pageSize, Action<int, Resp_GameList> callback)
{ {
if (!string.IsNullOrEmpty(searchKey)) if (!string.IsNullOrEmpty(searchKey))
{ {
@ -40,7 +39,7 @@ namespace AxibugEmuOnline.Client
//string utf8String = Encoding.UTF8.GetString(utf8Bytes); //string utf8String = Encoding.UTF8.GetString(utf8Bytes);
//searchKey = UrlEncode(utf8String); //searchKey = UrlEncode(utf8String);
//App.log.Info($"search->{utf8String} ->{searchKey}"); //App.log.Info($"search->{utf8String} ->{searchKey}");
string url = $"{WebSiteApi}/NesRomList?Page={page}&PageSize={pageSize}&SearchKey={searchKey}"; string url = $"{WebSiteApi}/RomList?Page={page}&PageSize={pageSize}&SearchKey={searchKey}&Token={App.user.Token}";
App.log.Info($"GetRomList=>{url}"); App.log.Info($"GetRomList=>{url}");
AxiHttpProxy.SendWebRequestProxy request = AxiHttpProxy.Get(url); AxiHttpProxy.SendWebRequestProxy request = AxiHttpProxy.Get(url);
yield return request.SendWebRequest; yield return request.SendWebRequest;
@ -73,7 +72,7 @@ namespace AxibugEmuOnline.Client
} }
private IEnumerator GetRomListFlow(AxibugProtobuf.RomPlatformType platform, int page, int pageSize, Action<int, Resp_GameList> callback) private IEnumerator GetRomListFlow(AxibugProtobuf.RomPlatformType platform, int page, int pageSize, Action<int, Resp_GameList> callback)
{ {
string url = $"{WebSiteApi}/RomList?Page={page}&PageSize={pageSize}&PType={(int)platform}"; string url = $"{WebSiteApi}/RomList?Page={page}&PageSize={pageSize}&PType={(int)platform}&Token={App.user.Token}";
App.log.Info($"GetRomList=>{url}"); App.log.Info($"GetRomList=>{url}");
AxiHttpProxy.SendWebRequestProxy request = AxiHttpProxy.Get(url); AxiHttpProxy.SendWebRequestProxy request = AxiHttpProxy.Get(url);
yield return request.SendWebRequest; yield return request.SendWebRequest;
@ -105,10 +104,101 @@ namespace AxibugEmuOnline.Client
*/ */
} }
public void GetMarkList(Action<int, Resp_GameList> callback, AxibugProtobuf.RomPlatformType platform, int page, int pageSize = 10)
{
App.StartCoroutine(GetMarkListFlow(platform, page, pageSize, callback));
}
public void SearchMarkList(Action<int, Resp_GameList> callback, AxibugProtobuf.RomPlatformType platform, string searchKey, int page, int pageSize = 10)
{
App.StartCoroutine(SearchMarkListFlow(platform, searchKey, page, pageSize, callback));
}
private IEnumerator SearchMarkListFlow(AxibugProtobuf.RomPlatformType platform, string searchKey, int page, int pageSize, Action<int, Resp_GameList> callback)
{
if (!string.IsNullOrEmpty(searchKey))
{
string oldsearch = searchKey;
//searchKey = System.Net.WebUtility.UrlEncode(searchKey);
searchKey = AxiHttp.UrlEncode(searchKey);
App.log.Info($"search->{oldsearch} ->{searchKey}");
//searchKey = HttpUtility.UrlDecode(searchKey);
}
//避免特殊字符和个别文字编码问题
//byte[] gb2312Bytes = Encoding.Default.GetBytes(searchKey);
//byte[] utf8Bytes = Encoding.Convert(Encoding.Default, Encoding.UTF8, gb2312Bytes);
//// 将UTF-8编码的字节数组转换回字符串此时是UTF-8编码的字符串
//string utf8String = Encoding.UTF8.GetString(utf8Bytes);
//searchKey = UrlEncode(utf8String);
//App.log.Info($"search->{utf8String} ->{searchKey}");
string url = $"{WebSiteApi}/RomList?Page={page}&PageSize={pageSize}&SearchKey={searchKey}&Token={App.user.Token}";
App.log.Info($"GetRomList=>{url}");
AxiHttpProxy.SendWebRequestProxy request = AxiHttpProxy.Get(url);
yield return request.SendWebRequest;
if (!request.downloadHandler.isDone)
{
callback.Invoke(page, null);
yield break;
}
if (!request.downloadHandler.bHadErr)
{
var resp = JsonUtility.FromJson<Resp_GameList>(request.downloadHandler.text);
callback.Invoke(page, resp);
yield break;
}
App.log.Error(request.downloadHandler.ErrInfo);
callback.Invoke(page, null);
/*
UnityWebRequest request = UnityWebRequest.Get($"{WebSiteApi}/NesRomList?Page={page}&PageSize={pageSize}&SearchKey={searchKey}");
yield return request.SendWebRequest();
if (request.result != UnityWebRequest.Result.Success)
{
callback.Invoke(null);
yield break;
}*/
}
private IEnumerator GetMarkListFlow(AxibugProtobuf.RomPlatformType platform, int page, int pageSize, Action<int, Resp_GameList> callback)
{
string url = $"{WebSiteApi}/RomList?Page={page}&PageSize={pageSize}&PType={(int)platform}&Token={App.user.Token}";
App.log.Info($"GetRomList=>{url}");
AxiHttpProxy.SendWebRequestProxy request = AxiHttpProxy.Get(url);
yield return request.SendWebRequest;
if (!request.downloadHandler.isDone)
{
callback.Invoke(page, null);
yield break;
}
//请求成功
if (!request.downloadHandler.bHadErr)
{
var resp = JsonUtility.FromJson<Resp_GameList>(request.downloadHandler.text);
callback.Invoke(page, resp);
yield break;
}
App.log.Error(request.downloadHandler.ErrInfo);
callback.Invoke(page, null);
/*
UnityWebRequest request = UnityWebRequest.Get($"{WebSiteApi}/NesRomList?Page={page}&PageSize={pageSize}");
yield return request.SendWebRequest();
if (request.result != UnityWebRequest.Result.Success)
{
callback.Invoke(null);
yield break;
}
*/
}
public IEnumerator GetRomInfo(int RomID, Action<Resp_RomInfo> callback) public IEnumerator GetRomInfo(int RomID, Action<Resp_RomInfo> callback)
{ {
AxiHttpProxy.SendWebRequestProxy request = AxiHttpProxy.Get($"{WebSiteApi}/RomInfo?RomID={RomID}"); AxiHttpProxy.SendWebRequestProxy request = AxiHttpProxy.Get($"{WebSiteApi}/RomInfo?RomID={RomID}&Token={App.user.Token}");
yield return request.SendWebRequest; yield return request.SendWebRequest;
if (!request.downloadHandler.isDone) if (!request.downloadHandler.isDone)
{ {
@ -184,7 +274,14 @@ namespace AxibugEmuOnline.Client
public string imgUrl; public string imgUrl;
public string hash; public string hash;
public int stars; public int stars;
public int isStar;//TODO 实现收藏标记 /// <summary>
/// 游玩计数
/// </summary>
public int playcount;
/// <summary>
/// 是否收藏
/// </summary>
public int isStar;
} }
[Serializable] [Serializable]
public class Resp_CheckStandInfo public class Resp_CheckStandInfo

View File

@ -31,8 +31,8 @@ namespace AxibugEmuOnline.Client
switch (platform) switch (platform)
{ {
case RomPlatformType.Nes: case RomPlatformType.Nes:
m_romGetFunc = App.httpAPI.GetNesRomList; m_romGetFunc = App.httpAPI.GetRomList;
m_romSearchFunc = App.httpAPI.SearchNesRomList; m_romSearchFunc = App.httpAPI.SearchRomList;
break; break;
} }

View File

@ -18,6 +18,7 @@ namespace AxibugEmuOnline.Client.Manager
public class MainUserDataBase : UserDataBase public class MainUserDataBase : UserDataBase
{ {
public bool IsLoggedIn { get; set; } = false; public bool IsLoggedIn { get; set; } = false;
public string Token { get; set; }
} }
public class UserDataManager public class UserDataManager
@ -39,13 +40,18 @@ namespace AxibugEmuOnline.Client.Manager
public MainUserDataBase userdata { get; private set; } = new MainUserDataBase(); public MainUserDataBase userdata { get; private set; } = new MainUserDataBase();
public bool IsLoggedIn => userdata.IsLoggedIn; public bool IsLoggedIn => userdata.IsLoggedIn;
public string Token => userdata.IsLoggedIn ? userdata.Token : string.Empty;
Dictionary<long, UserDataBase> DictUID2User = new Dictionary<long, UserDataBase>(); Dictionary<long, UserDataBase> DictUID2User = new Dictionary<long, UserDataBase>();
public int OnlinePlayerCount => DictUID2User.Count; public int OnlinePlayerCount => DictUID2User.Count;
public void InitMainUserData(string UName, long UID) public void InitMainUserData(string UName, long UID, string token)
{ {
userdata.NickName = UName; userdata.NickName = UName;
userdata.IsLoggedIn = true; userdata.IsLoggedIn = true;
userdata.UID = UID; userdata.UID = UID;
userdata.Token = token;
#if UNITY_EDITOR
App.log.Debug($"收到登录token:{token}");
#endif
//以及其他数据初始化 //以及其他数据初始化
//... //...
} }

View File

@ -9,7 +9,6 @@ using UnityEditor;
using UnityEngine; using UnityEngine;
using VirtualNes.Core; using VirtualNes.Core;
using VirtualNes.Core.Debug; using VirtualNes.Core.Debug;
using Debug = System.Diagnostics.Debug;
namespace AxibugEmuOnline.Client namespace AxibugEmuOnline.Client
{ {
@ -196,7 +195,7 @@ namespace AxibugEmuOnline.Client
var xmlStr = File.ReadAllText("nes20db.xml"); var xmlStr = File.ReadAllText("nes20db.xml");
var xml = XDocument.Parse(xmlStr); var xml = XDocument.Parse(xmlStr);
var games = xml.Element("nes20db")?.Elements("game"); var games = xml.Element("nes20db")?.Elements("game");
Debug.Assert(games != null, nameof(games) + " != null"); System.Diagnostics.Debug.Assert(games != null, nameof(games) + " != null");
foreach (var game in games) foreach (var game in games)
{ {
var crcStr = game.Element("rom")?.Attribute("crc32")?.Value; var crcStr = game.Element("rom")?.Attribute("crc32")?.Value;

View File

@ -128,9 +128,9 @@ namespace AxibugEmuOnline.Client
{ {
var romItem = m_currentSelect; var romItem = m_currentSelect;
if (!romItem.IsStar) if (!romItem.IsStar)
App.share.SendGameStar(romItem.RomID, 0);
else
App.share.SendGameStar(romItem.RomID, 1); App.share.SendGameStar(romItem.RomID, 1);
else
App.share.SendGameStar(romItem.RomID, 0);
} }
} }
} }

View File

@ -1,5 +1,6 @@
using AxibugEmuOnline.Client.ClientCore; using AxibugEmuOnline.Client.ClientCore;
using AxibugEmuOnline.Client.Event; using AxibugEmuOnline.Client.Event;
using UnityEngine;
namespace AxibugEmuOnline.Client namespace AxibugEmuOnline.Client
{ {

View File

@ -8,6 +8,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Google.Protobuf" Version="3.26.1" />
<PackageReference Include="MySql.Data" Version="9.1.0" /> <PackageReference Include="MySql.Data" Version="9.1.0" />
</ItemGroup> </ItemGroup>
@ -20,4 +21,10 @@
</Reference> </Reference>
</ItemGroup> </ItemGroup>
<ItemGroup>
<None Update="config.cfg">
<CopyToOutputDirectory>Never</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project> </Project>

View File

@ -0,0 +1,147 @@
using System.Security.Cryptography;
using System.Text;
namespace AxibugEmuOnline.Server.Common
{
public static class AESHelper
{
static byte[] currKey;
static byte[] currIV;
public static void LoadKeyIVCfg(string key, string vi)
{
try
{
currKey = CommaSeparatedStringToByteArray(key);
currIV = CommaSeparatedStringToByteArray(key);
}
catch (Exception ex)
{
Console.WriteLine("aeskeyvi 配置错误"+ex.Message);
}
}
public static void LoadKeyIVCfg(byte[] key, byte[] vi)
{
currKey = key;
currIV = key;
}
public static void GenAesKeyIV()
{
Aes aes = Aes.Create();
aes.KeySize = 128;
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
aes.GenerateKey();
aes.GenerateIV();
string key = ByteArrayToCommaSeparatedString(aes.Key);
Console.WriteLine("key:");
Console.WriteLine(key);
string vi = ByteArrayToCommaSeparatedString(aes.IV);
Console.WriteLine("iv:");
Console.WriteLine(vi);
byte[] temp = new byte[255];
for (byte i = 0; i < temp.Length; i++)
temp[i] = i;
byte[] EncodeData = Encrypt(temp, aes.Key, aes.IV);
byte[] DecodeData = Decrypt(EncodeData, aes.Key, aes.IV);
bool bOk = true;
if (temp.Length != DecodeData.Length)
{
bOk = false;
}
else
{
for (int i = 0; i < temp.Length; i++)
{
if (temp[i] != DecodeData[i])
{
bOk = false;
break;
}
}
}
Console.WriteLine($"密钥和填充加解密验证:{bOk}");
}
public static string ByteArrayToCommaSeparatedString(byte[] byteArray)
{
if (byteArray == null)
throw new ArgumentNullException(nameof(byteArray));
StringBuilder sb = new StringBuilder();
for (int i = 0; i < byteArray.Length; i++)
{
sb.Append(byteArray[i]);
// 不是最后一个元素时,添加逗号
if (i < byteArray.Length - 1)
{
sb.Append(",");
}
}
return sb.ToString();
}
public static byte[] CommaSeparatedStringToByteArray(string commaSeparatedString)
{
if (string.IsNullOrEmpty(commaSeparatedString))
throw new ArgumentNullException(nameof(commaSeparatedString));
// 去除字符串两端的空格,并按逗号分割
string[] byteStrings = commaSeparatedString.Trim().Split(',');
// 将每个字符串转换成byte并存储到数组中
byte[] byteArray = byteStrings.Select(byteString =>
{
if (!byte.TryParse(byteString, out byte result))
throw new FormatException($"无法将字符串 '{byteString}' 解析为字节。");
return result;
}).ToArray();
return byteArray;
}
public static byte[] Encrypt(byte[] toEncryptArray)
{
return Encrypt(toEncryptArray, currKey, currIV);
}
public static byte[] Encrypt(byte[] toEncryptArray, byte[] keyArray, byte[] ivArray)
{
Aes rDel = Aes.Create();
rDel.Key = keyArray;
rDel.IV = ivArray;
rDel.Mode = CipherMode.CBC;
rDel.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = rDel.CreateEncryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
return resultArray;
}
public static byte[] Decrypt(byte[] toDecrypt)
{
return Decrypt(toDecrypt, currKey, currIV);
}
public static byte[] Decrypt(byte[] toDecrypt, byte[] keyArray, byte[] ivArray)
{
Aes rDel = Aes.Create();
rDel.Key = keyArray;
rDel.IV = ivArray;
rDel.Mode = CipherMode.CBC;
rDel.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = rDel.CreateDecryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toDecrypt, 0, toDecrypt.Length);
return resultArray;
}
}
}

View File

@ -19,6 +19,8 @@ namespace AxibugEmuOnline.Server.Common
public string ServerIp { get; set; } public string ServerIp { get; set; }
public ushort ServerPort { get; set; } public ushort ServerPort { get; set; }
public string ClientVersion { get; set; } public string ClientVersion { get; set; }
public string AesKey { get; set; }
public string AesIv { get; set; }
} }

View File

@ -2,18 +2,16 @@
namespace AxibugEmuOnline.Server.Common namespace AxibugEmuOnline.Server.Common
{ {
public static class Haoyue_SQLPoolManager public static class SQLPool
{ {
private static Queue<MySqlConnection> SQLPool = new Queue<MySqlConnection>(); static Queue<MySqlConnection> _ConQueue = new Queue<MySqlConnection>();
private static Dictionary<MySqlConnection, Haoyue_PoolTime> _OutOfSQLPool = new Dictionary<MySqlConnection, Haoyue_PoolTime>(); static Dictionary<MySqlConnection, Haoyue_PoolTime> _OutOfSQLPool = new Dictionary<MySqlConnection, Haoyue_PoolTime>();
private static Dictionary<string, long> _DicSqlRunFunNum = new Dictionary<string, long>(); static Dictionary<string, long> _DicSqlRunFunNum = new Dictionary<string, long>();
private static Dictionary<string, long> _DicTimeOutSqlRunFunNum = new Dictionary<string, long>(); static Dictionary<string, long> _DicTimeOutSqlRunFunNum = new Dictionary<string, long>();
private const int DefaultCount = 1; const int DefaultCount = 1;
private const int MaxLimit = 5; const int MaxLimit = 5;
private static readonly object _sync = new object(); static readonly object _sync = new object();
static MySqlConnectionStringBuilder connBuilder;
private static MySqlConnectionStringBuilder connBuilder;
public static void InitConnMgr() public static void InitConnMgr()
{ {
@ -33,9 +31,9 @@ namespace AxibugEmuOnline.Server.Common
{ {
MySqlConnection _conn = conn(); MySqlConnection _conn = conn();
_conn.Open(); _conn.Open();
SQLPool.Enqueue(_conn); _ConQueue.Enqueue(_conn);
} }
Console.WriteLine("SQLPool初始化完毕,连接数" + SQLPool.Count); Console.WriteLine("SQLPool初始化完毕,连接数" + _ConQueue.Count);
} }
public static MySqlConnection conn() public static MySqlConnection conn()
{ {
@ -55,22 +53,22 @@ namespace AxibugEmuOnline.Server.Common
_DicSqlRunFunNum[FuncStr] = 1L; _DicSqlRunFunNum[FuncStr] = 1L;
} }
MySqlConnection _conn = null; MySqlConnection _conn = null;
if (SQLPool.Count < 1) if (_ConQueue.Count < 1)
{ {
Console.WriteLine("[DequeueSQLConn]创建新的SQLPool.Count>" + SQLPool.Count); Console.WriteLine("[DequeueSQLConn]创建新的SQLPool.Count>" + _ConQueue.Count);
_conn = conn(); _conn = conn();
_conn.Open(); _conn.Open();
} }
else else
{ {
MySqlConnection temp = null; MySqlConnection temp = null;
while (SQLPool.Count > 0) while (_ConQueue.Count > 0)
{ {
Console.WriteLine("[DequeueSQLConn]取出一个SQLCount.Count>" + SQLPool.Count); Console.WriteLine("[DequeueSQLConn]取出一个SQLCount.Count>" + _ConQueue.Count);
temp = SQLPool.Dequeue(); temp = _ConQueue.Dequeue();
if (temp.State == System.Data.ConnectionState.Closed) if (temp.State == System.Data.ConnectionState.Closed)
{ {
Console.WriteLine("[DequeueSQLConn]已经断开SQLCount.Count>" + SQLPool.Count); Console.WriteLine("[DequeueSQLConn]已经断开SQLCount.Count>" + _ConQueue.Count);
temp.Dispose(); temp.Dispose();
temp = null; temp = null;
continue; continue;
@ -110,17 +108,17 @@ namespace AxibugEmuOnline.Server.Common
{ {
Console.WriteLine("出队遗漏的数据出现了!"); Console.WriteLine("出队遗漏的数据出现了!");
} }
if (SQLPool.Count > MaxLimit) if (_ConQueue.Count > MaxLimit)
{ {
Console.WriteLine("已经不需要回收了,多余了,SQLPool.Count>" + SQLPool.Count); Console.WriteLine("已经不需要回收了,多余了,SQLPool.Count>" + _ConQueue.Count);
BackConn.Close(); BackConn.Close();
BackConn.Dispose(); BackConn.Dispose();
BackConn = null; BackConn = null;
} }
else else
{ {
SQLPool.Enqueue(BackConn); _ConQueue.Enqueue(BackConn);
Console.WriteLine("回收SQLPool.Count>" + SQLPool.Count); Console.WriteLine("回收SQLPool.Count>" + _ConQueue.Count);
} }
} }
} }
@ -143,15 +141,15 @@ namespace AxibugEmuOnline.Server.Common
{ {
_DicTimeOutSqlRunFunNum[o2.Value.FuncStr] = 1L; _DicTimeOutSqlRunFunNum[o2.Value.FuncStr] = 1L;
} }
if (SQLPool.Count > MaxLimit) if (_ConQueue.Count > MaxLimit)
{ {
Console.WriteLine("[超时回收]" + o2.Value.FuncStr + "已经不需要回收了,多余了,SQLPool.Count>" + SQLPool.Count); Console.WriteLine("[超时回收]" + o2.Value.FuncStr + "已经不需要回收了,多余了,SQLPool.Count>" + _ConQueue.Count);
o2.Key.Close(); o2.Key.Close();
} }
else else
{ {
Console.WriteLine("[超时回收]" + o2.Value.FuncStr + "回收SQLPool.Count>" + SQLPool.Count); Console.WriteLine("[超时回收]" + o2.Value.FuncStr + "回收SQLPool.Count>" + _ConQueue.Count);
SQLPool.Enqueue(o2.Key); _ConQueue.Enqueue(o2.Key);
} }
removeTemp.Add(o2.Key); removeTemp.Add(o2.Key);
} }
@ -172,7 +170,7 @@ namespace AxibugEmuOnline.Server.Common
Console.WriteLine("[超时回收]_OutOfSQLPool清理异常"); Console.WriteLine("[超时回收]_OutOfSQLPool清理异常");
} }
} }
Console.WriteLine("[超时回收]处理结束SQLPool.Count>" + SQLPool.Count); Console.WriteLine("[超时回收]处理结束SQLPool.Count>" + _ConQueue.Count);
} }
} }
public static long time() public static long time()

View File

@ -22,7 +22,8 @@ namespace AxibugEmuOnline.Server
{ {
g_Log = new LogManager(); g_Log = new LogManager();
Config.LoadConfig(); Config.LoadConfig();
Haoyue_SQLPoolManager.InitConnMgr(); AESHelper.LoadKeyIVCfg(Config.cfg.AesKey, Config.cfg.AesIv);
SQLPool.InitConnMgr();
g_Tick = new TickManager(); g_Tick = new TickManager();
g_ClientMgr = new ClientManager(); g_ClientMgr = new ClientManager();
g_ClientMgr.Init(45000, 120); g_ClientMgr.Init(45000, 120);

View File

@ -3,7 +3,6 @@ using AxibugEmuOnline.Server.NetWork;
using AxibugProtobuf; using AxibugProtobuf;
using MySql.Data.MySqlClient; using MySql.Data.MySqlClient;
using System.Net.Sockets; using System.Net.Sockets;
using System.Security.Policy;
namespace AxibugEmuOnline.Server.Manager namespace AxibugEmuOnline.Server.Manager
{ {
@ -21,28 +20,27 @@ namespace AxibugEmuOnline.Server.Manager
ClientInfo _c = AppSrv.g_ClientMgr.GetClientForSocket(_socket); ClientInfo _c = AppSrv.g_ClientMgr.GetClientForSocket(_socket);
Protobuf_Game_Mark_RESP respData = new Protobuf_Game_Mark_RESP(); Protobuf_Game_Mark_RESP respData = new Protobuf_Game_Mark_RESP();
MySqlConnection conn = Haoyue_SQLPoolManager.DequeueSQLConn("RecvGameMark"); MySqlConnection conn = SQLPool.DequeueSQLConn("RecvGameMark");
try try
{ {
string query = "SELECT id from rom_stars where uid = ?uid and romid = ?platform and platform = ?romid"; string query = "SELECT id from rom_stars where uid = ?uid and romid = ?romid";
bool bHad = false; bool bHad = false;
using (var command = new MySqlCommand(query, conn)) using (var command = new MySqlCommand(query, conn))
{ {
// 设置参数值 // 设置参数值
command.Parameters.AddWithValue("?uid", _c.UID); command.Parameters.AddWithValue("?uid", _c.UID);
command.Parameters.AddWithValue("?platform", 1);
command.Parameters.AddWithValue("?romid", msg.RomID); command.Parameters.AddWithValue("?romid", msg.RomID);
using (var reader = command.ExecuteReader()) using (var reader = command.ExecuteReader())
{ {
while (reader.Read()) while (reader.Read())
{ {
if (reader.GetInt32(0) > 0) reader.GetInt32(0);
bHad = true;
} }
} }
} }
if (msg.State == 0) //收藏
if (msg.Motion == 1)
{ {
if (bHad) if (bHad)
{ {
@ -92,18 +90,81 @@ namespace AxibugEmuOnline.Server.Manager
catch (Exception e) catch (Exception e)
{ {
} }
Haoyue_SQLPoolManager.EnqueueSQLConn(conn);
respData.Stars = GetRomStart(msg.RomID);
respData.IsStar = CheckIsRomStar(msg.RomID, _c.UID) ? 1 : 0;
SQLPool.EnqueueSQLConn(conn);
respData.RomID = msg.RomID; respData.RomID = msg.RomID;
AppSrv.g_ClientMgr.ClientSend(_c, (int)CommandID.CmdGameMark, (int)ErrorCode.ErrorOk, ProtoBufHelper.Serizlize(respData)); AppSrv.g_ClientMgr.ClientSend(_c, (int)CommandID.CmdGameMark, (int)ErrorCode.ErrorOk, ProtoBufHelper.Serizlize(respData));
} }
public int GetRomStart(int RomId)
{
int stars = 0;
MySqlConnection conn = SQLPool.DequeueSQLConn("GetStart");
try
{
string query = $"SELECT `stars` FROM romlist where id = ?romid;";
using (var command = new MySqlCommand(query, conn))
{
// 设置参数值
command.Parameters.AddWithValue("?RomID", RomId);
// 执行查询并处理结果
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
stars = reader.GetInt32(0);
}
}
}
}
catch (Exception e)
{
AppSrv.g_Log.Error(e);
}
SQLPool.EnqueueSQLConn(conn);
return stars;
}
public bool CheckIsRomStar(int RomId, long uid)
{
bool bhad = false;
MySqlConnection conn = SQLPool.DequeueSQLConn("CheckIsRomStart");
try
{
string query = $"SELECT count(0) from rom_stars where uid = ?uid and = ?romid";
using (var command = new MySqlCommand(query, conn))
{
// 设置参数值
command.Parameters.AddWithValue("?RomID", RomId);
command.Parameters.AddWithValue("?uid", uid);
// 执行查询并处理结果
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
bhad = reader.GetInt32(0) > 0;
}
}
}
}
catch (Exception e)
{
AppSrv.g_Log.Error(e);
}
SQLPool.EnqueueSQLConn(conn);
return bhad;
}
public RomPlatformType GetRomPlatformType(int RomID) public RomPlatformType GetRomPlatformType(int RomID)
{ {
if (mDictRomID2Platform.TryGetValue(RomID, out RomPlatformType ptype)) if (mDictRomID2Platform.TryGetValue(RomID, out RomPlatformType ptype))
return ptype; return ptype;
ptype = RomPlatformType.Invalid; ptype = RomPlatformType.Invalid;
MySqlConnection conn = Haoyue_SQLPoolManager.DequeueSQLConn("GetRomPlatformType"); MySqlConnection conn = SQLPool.DequeueSQLConn("GetRomPlatformType");
try try
{ {
string query = "SELECT PlatformType from romlist where Id = ?RomID "; string query = "SELECT PlatformType from romlist where Id = ?RomID ";
@ -129,7 +190,7 @@ namespace AxibugEmuOnline.Server.Manager
if (ptype == RomPlatformType.Invalid) if (ptype == RomPlatformType.Invalid)
AppSrv.g_Log.Error($"RomID {RomID} 没找到平台配置"); AppSrv.g_Log.Error($"RomID {RomID} 没找到平台配置");
Haoyue_SQLPoolManager.EnqueueSQLConn(conn); SQLPool.EnqueueSQLConn(conn);
return ptype; return ptype;
} }

View File

@ -3,19 +3,29 @@ using AxibugEmuOnline.Server.Event;
using AxibugEmuOnline.Server.NetWork; using AxibugEmuOnline.Server.NetWork;
using AxibugProtobuf; using AxibugProtobuf;
using MySql.Data.MySqlClient; using MySql.Data.MySqlClient;
using Mysqlx;
using Org.BouncyCastle.Asn1.X9;
using Org.BouncyCastle.Ocsp; using Org.BouncyCastle.Ocsp;
using System.Collections;
using System.Net.Sockets; using System.Net.Sockets;
namespace AxibugEmuOnline.Server.Manager namespace AxibugEmuOnline.Server.Manager
{ {
public class LoginManager public class LoginManager
{ {
static long tokenSeed = 1;
public LoginManager() public LoginManager()
{ {
NetMsg.Instance.RegNetMsgEvent((int)CommandID.CmdLogin, UserLogin); NetMsg.Instance.RegNetMsgEvent((int)CommandID.CmdLogin, UserLogin);
NetMsg.Instance.RegNetMsgEvent((int)CommandID.CmdModifyNickName, OnCmdModifyNickName); NetMsg.Instance.RegNetMsgEvent((int)CommandID.CmdModifyNickName, OnCmdModifyNickName);
} }
static long GetNextTokenSeed()
{
return tokenSeed++;
}
void UserLogin(Socket _socket, byte[] reqData) void UserLogin(Socket _socket, byte[] reqData)
{ {
AppSrv.g_Log.DebugCmd("UserLogin"); AppSrv.g_Log.DebugCmd("UserLogin");
@ -49,6 +59,8 @@ namespace AxibugEmuOnline.Server.Manager
UpdateUserData(_uid, _c, msg.DeviceType); UpdateUserData(_uid, _c, msg.DeviceType);
string tokenstr = GenToken(_c);
EventSystem.Instance.PostEvent(EEvent.OnUserOnline, _c.UID); EventSystem.Instance.PostEvent(EEvent.OnUserOnline, _c.UID);
byte[] respData = ProtoBufHelper.Serizlize(new Protobuf_Login_RESP() byte[] respData = ProtoBufHelper.Serizlize(new Protobuf_Login_RESP()
@ -56,10 +68,11 @@ namespace AxibugEmuOnline.Server.Manager
Status = LoginResultStatus.Ok, Status = LoginResultStatus.Ok,
RegDate = _c.RegisterDT.ToString("yyyy-MM-dd HH:mm:ss"), RegDate = _c.RegisterDT.ToString("yyyy-MM-dd HH:mm:ss"),
LastLoginDate = _c.LastLogInDT.ToString("yyyy-MM-dd HH:mm:ss"), LastLoginDate = _c.LastLogInDT.ToString("yyyy-MM-dd HH:mm:ss"),
Token = "", Token = tokenstr,
NickName = _c.NickName, NickName = _c.NickName,
UID = _c.UID UID = _c.UID
}); });
AppSrv.g_Log.Info($"玩家登录成功 UID->{_c.UID} NikeName->{_c.NickName}"); AppSrv.g_Log.Info($"玩家登录成功 UID->{_c.UID} NikeName->{_c.NickName}");
AppSrv.g_ClientMgr.ClientSend(_c, (int)CommandID.CmdLogin, (int)ErrorCode.ErrorOk, respData); AppSrv.g_ClientMgr.ClientSend(_c, (int)CommandID.CmdLogin, (int)ErrorCode.ErrorOk, respData);
} }
@ -70,7 +83,7 @@ namespace AxibugEmuOnline.Server.Manager
bool bDone = false; bool bDone = false;
ClientInfo _c = AppSrv.g_ClientMgr.GetClientForSocket(socket); ClientInfo _c = AppSrv.g_ClientMgr.GetClientForSocket(socket);
Protobuf_Modify_NickName msg = ProtoBufHelper.DeSerizlize<Protobuf_Modify_NickName>(reqData); Protobuf_Modify_NickName msg = ProtoBufHelper.DeSerizlize<Protobuf_Modify_NickName>(reqData);
MySqlConnection conn = Haoyue_SQLPoolManager.DequeueSQLConn("ModifyNikeName"); MySqlConnection conn = SQLPool.DequeueSQLConn("ModifyNikeName");
try try
{ {
string query = "update users set nikename = ?nikename where uid = ?uid "; string query = "update users set nikename = ?nikename where uid = ?uid ";
@ -88,7 +101,7 @@ namespace AxibugEmuOnline.Server.Manager
catch (Exception e) catch (Exception e)
{ {
} }
Haoyue_SQLPoolManager.EnqueueSQLConn(conn); SQLPool.EnqueueSQLConn(conn);
if (bDone) if (bDone)
{ {
@ -123,7 +136,7 @@ namespace AxibugEmuOnline.Server.Manager
{ {
uid = 0; uid = 0;
bool bDone = true; bool bDone = true;
MySqlConnection conn = Haoyue_SQLPoolManager.DequeueSQLConn("GetUidByDevice"); MySqlConnection conn = SQLPool.DequeueSQLConn("GetUidByDevice");
try try
{ {
string query = "SELECT uid from user_devices where device = ?deviceStr "; string query = "SELECT uid from user_devices where device = ?deviceStr ";
@ -193,7 +206,7 @@ namespace AxibugEmuOnline.Server.Manager
AppSrv.g_Log.Error($"ex=>{e.ToString()}"); AppSrv.g_Log.Error($"ex=>{e.ToString()}");
bDone = false; bDone = false;
} }
Haoyue_SQLPoolManager.EnqueueSQLConn(conn); SQLPool.EnqueueSQLConn(conn);
if (uid <= 0) if (uid <= 0)
bDone = false; bDone = false;
@ -202,7 +215,7 @@ namespace AxibugEmuOnline.Server.Manager
public void UpdateUserData(long uid, ClientInfo _c, DeviceType deviceType) public void UpdateUserData(long uid, ClientInfo _c, DeviceType deviceType)
{ {
MySqlConnection conn = Haoyue_SQLPoolManager.DequeueSQLConn("UpdateUserData"); MySqlConnection conn = SQLPool.DequeueSQLConn("UpdateUserData");
try try
{ {
string query = "SELECT account,nikename,regdate,lastlogindate from users where uid = ?uid "; string query = "SELECT account,nikename,regdate,lastlogindate from users where uid = ?uid ";
@ -236,7 +249,30 @@ namespace AxibugEmuOnline.Server.Manager
{ {
} }
Haoyue_SQLPoolManager.EnqueueSQLConn(conn); SQLPool.EnqueueSQLConn(conn);
}
static string GenToken(ClientInfo _c)
{
long timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
Protobuf_Token_Struct _resp = new Protobuf_Token_Struct()
{
UID = _c.UID,
TokenGenDate = timestamp,
Seed = GetNextTokenSeed()
};
byte[] protobufData = ProtoBufHelper.Serizlize(_resp);
ProtoBufHelper.DeSerizlize<Protobuf_Token_Struct>(protobufData);
byte[] encryptData = AESHelper.Encrypt(protobufData);
string tobase64 = Convert.ToBase64String(encryptData);
return tobase64;
}
static Protobuf_Token_Struct DecrypToken(string tokenStr)
{
byte[] encryptData = Convert.FromBase64String(tokenStr);
byte[] decryptData = AESHelper.Decrypt(encryptData);
return ProtoBufHelper.DeSerizlize<Protobuf_Token_Struct>(decryptData);
} }
public string GetRandomNickName(long uid) public string GetRandomNickName(long uid)
@ -450,5 +486,7 @@ namespace AxibugEmuOnline.Server.Manager
"红白机战士之魂", "红白机战士之魂",
"超级时间探险家" "超级时间探险家"
]; ];
} }
} }

View File

@ -109,7 +109,7 @@ namespace AxibugEmuOnline.Server
} }
public void RoomLog(long uid, int platform, int RoomID, int RomID, RoomLogType state) public void RoomLog(long uid, int platform, int RoomID, int RomID, RoomLogType state)
{ {
MySqlConnection conn = Haoyue_SQLPoolManager.DequeueSQLConn("RoomLog"); MySqlConnection conn = SQLPool.DequeueSQLConn("RoomLog");
try try
{ {
string query = "INSERT INTO `haoyue_emu`.`room_log` (`uid`, `platform`, `romid`,`roomid`, `state`) VALUES ( ?uid, ?platform, ?romid, ?roomid, ?state);"; string query = "INSERT INTO `haoyue_emu`.`room_log` (`uid`, `platform`, `romid`,`roomid`, `state`) VALUES ( ?uid, ?platform, ?romid, ?roomid, ?state);";
@ -137,7 +137,7 @@ namespace AxibugEmuOnline.Server
catch (Exception e) catch (Exception e)
{ {
} }
Haoyue_SQLPoolManager.EnqueueSQLConn(conn); SQLPool.EnqueueSQLConn(conn);
} }
#endregion #endregion

View File

@ -77,6 +77,11 @@ namespace AxibugEmuOnline.Server
UpdateRomHash(); UpdateRomHash();
} }
break; break;
case "aesgen":
{
AESHelper.GenAesKeyIV();
}
break;
default: default:
Console.WriteLine("未知命令" + CommandStr); Console.WriteLine("未知命令" + CommandStr);
break; break;
@ -88,7 +93,7 @@ namespace AxibugEmuOnline.Server
static void UpdateRomHash() static void UpdateRomHash()
{ {
AppSrv.g_Log.Info("UpdateRomHash"); AppSrv.g_Log.Info("UpdateRomHash");
MySqlConnection conn = Haoyue_SQLPoolManager.DequeueSQLConn("UpdateRomHash"); MySqlConnection conn = SQLPool.DequeueSQLConn("UpdateRomHash");
try try
{ {
List<(int id, string romurl, string name)> list = new List<(int id, string romurl, string name)>(); List<(int id, string romurl, string name)> list = new List<(int id, string romurl, string name)>();
@ -139,7 +144,7 @@ namespace AxibugEmuOnline.Server
{ {
AppSrv.g_Log.Info($"err:{e.ToString()}"); AppSrv.g_Log.Info($"err:{e.ToString()}");
} }
Haoyue_SQLPoolManager.EnqueueSQLConn(conn); SQLPool.EnqueueSQLConn(conn);
} }
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -7,6 +7,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Google.Protobuf" Version="3.26.1" />
<PackageReference Include="MySql.Data" Version="9.0.0" /> <PackageReference Include="MySql.Data" Version="9.0.0" />
</ItemGroup> </ItemGroup>

View File

@ -0,0 +1,147 @@
using System.Security.Cryptography;
using System.Text;
namespace AxibugEmuOnline.Web.Common
{
public static class AESHelper
{
static byte[] currKey;
static byte[] currIV;
public static void LoadKeyIVCfg(string key, string vi)
{
try
{
currKey = CommaSeparatedStringToByteArray(key);
currIV = CommaSeparatedStringToByteArray(key);
}
catch (Exception ex)
{
Console.WriteLine("aeskeyvi 配置错误"+ex.Message);
}
}
public static void LoadKeyIVCfg(byte[] key, byte[] vi)
{
currKey = key;
currIV = key;
}
public static void GenAesKeyIV()
{
Aes aes = Aes.Create();
aes.KeySize = 128;
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
aes.GenerateKey();
aes.GenerateIV();
string key = ByteArrayToCommaSeparatedString(aes.Key);
Console.WriteLine("key:");
Console.WriteLine(key);
string vi = ByteArrayToCommaSeparatedString(aes.IV);
Console.WriteLine("iv:");
Console.WriteLine(vi);
byte[] temp = new byte[255];
for (byte i = 0; i < temp.Length; i++)
temp[i] = i;
byte[] EncodeData = Encrypt(temp, aes.Key, aes.IV);
byte[] DecodeData = Decrypt(EncodeData, aes.Key, aes.IV);
bool bOk = true;
if (temp.Length != DecodeData.Length)
{
bOk = false;
}
else
{
for (int i = 0; i < temp.Length; i++)
{
if (temp[i] != DecodeData[i])
{
bOk = false;
break;
}
}
}
Console.WriteLine($"密钥和填充加解密验证:{bOk}");
}
public static string ByteArrayToCommaSeparatedString(byte[] byteArray)
{
if (byteArray == null)
throw new ArgumentNullException(nameof(byteArray));
StringBuilder sb = new StringBuilder();
for (int i = 0; i < byteArray.Length; i++)
{
sb.Append(byteArray[i]);
// 不是最后一个元素时,添加逗号
if (i < byteArray.Length - 1)
{
sb.Append(",");
}
}
return sb.ToString();
}
public static byte[] CommaSeparatedStringToByteArray(string commaSeparatedString)
{
if (string.IsNullOrEmpty(commaSeparatedString))
throw new ArgumentNullException(nameof(commaSeparatedString));
// 去除字符串两端的空格,并按逗号分割
string[] byteStrings = commaSeparatedString.Trim().Split(',');
// 将每个字符串转换成byte并存储到数组中
byte[] byteArray = byteStrings.Select(byteString =>
{
if (!byte.TryParse(byteString, out byte result))
throw new FormatException($"无法将字符串 '{byteString}' 解析为字节。");
return result;
}).ToArray();
return byteArray;
}
public static byte[] Encrypt(byte[] toEncryptArray)
{
return Encrypt(toEncryptArray, currKey, currIV);
}
public static byte[] Encrypt(byte[] toEncryptArray, byte[] keyArray, byte[] ivArray)
{
Aes rDel = Aes.Create();
rDel.Key = keyArray;
rDel.IV = ivArray;
rDel.Mode = CipherMode.CBC;
rDel.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = rDel.CreateEncryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
return resultArray;
}
public static byte[] Decrypt(byte[] toDecrypt)
{
return Decrypt(toDecrypt, currKey, currIV);
}
public static byte[] Decrypt(byte[] toDecrypt, byte[] keyArray, byte[] ivArray)
{
Aes rDel = Aes.Create();
rDel.Key = keyArray;
rDel.IV = ivArray;
rDel.Mode = CipherMode.CBC;
rDel.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = rDel.CreateDecryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toDecrypt, 0, toDecrypt.Length);
return resultArray;
}
}
}

View File

@ -19,6 +19,8 @@ namespace AxibugEmuOnline.Web.Common
public string ServerIp { get; set; } public string ServerIp { get; set; }
public ushort ServerPort { get; set; } public ushort ServerPort { get; set; }
public string ClientVersion { get; set; } public string ClientVersion { get; set; }
public string AesKey { get; set; }
public string AesIv { get; set; }
} }

View File

@ -0,0 +1,22 @@
using Google.Protobuf;
namespace AxibugEmuOnline.Web.Common
{
public static class ProtoBufHelper
{
public static byte[] Serizlize(IMessage msg)
{
return msg.ToByteArray();
}
public static T DeSerizlize<T>(byte[] bytes)
{
var msgType = typeof(T);
object msg = Activator.CreateInstance(msgType);
((IMessage)msg).MergeFrom(bytes);
return (T)msg;
}
}
}

View File

@ -3,18 +3,16 @@ using MySql.Data.MySqlClient;
namespace AxibugEmuOnline.Web.Common namespace AxibugEmuOnline.Web.Common
{ {
public static class Haoyue_SQLPoolManager public static class SQLPool
{ {
private static Queue<MySqlConnection> SQLPool = new Queue<MySqlConnection>(); static Queue<MySqlConnection> _ConQueue = new Queue<MySqlConnection>();
private static Dictionary<MySqlConnection, Haoyue_PoolTime> _OutOfSQLPool = new Dictionary<MySqlConnection, Haoyue_PoolTime>(); static Dictionary<MySqlConnection, Haoyue_PoolTime> _OutOfSQLPool = new Dictionary<MySqlConnection, Haoyue_PoolTime>();
private static Dictionary<string, long> _DicSqlRunFunNum = new Dictionary<string, long>(); static Dictionary<string, long> _DicSqlRunFunNum = new Dictionary<string, long>();
private static Dictionary<string, long> _DicTimeOutSqlRunFunNum = new Dictionary<string, long>(); static Dictionary<string, long> _DicTimeOutSqlRunFunNum = new Dictionary<string, long>();
private const int DefaultCount = 1; const int DefaultCount = 1;
private const int MaxLimit = 5; const int MaxLimit = 5;
private static readonly object _sync = new object(); static readonly object _sync = new object();
static MySqlConnectionStringBuilder connBuilder;
private static MySqlConnectionStringBuilder connBuilder;
public static void InitConnMgr() public static void InitConnMgr()
{ {
@ -34,9 +32,9 @@ namespace AxibugEmuOnline.Web.Common
{ {
MySqlConnection _conn = conn(); MySqlConnection _conn = conn();
_conn.Open(); _conn.Open();
SQLPool.Enqueue(_conn); _ConQueue.Enqueue(_conn);
} }
Console.WriteLine("SQLPool初始化完毕,连接数" + SQLPool.Count); Console.WriteLine("SQLPool初始化完毕,连接数" + _ConQueue.Count);
} }
public static MySqlConnection conn() public static MySqlConnection conn()
{ {
@ -55,23 +53,47 @@ namespace AxibugEmuOnline.Web.Common
{ {
_DicSqlRunFunNum[FuncStr] = 1L; _DicSqlRunFunNum[FuncStr] = 1L;
} }
MySqlConnection _conn; MySqlConnection _conn = null;
if (SQLPool.Count < 1) if (_ConQueue.Count < 1)
{ {
Console.WriteLine("[DequeueSQLConn]创建新的SQLPool.Count>" + SQLPool.Count); Console.WriteLine("[DequeueSQLConn]创建新的SQLPool.Count>" + _ConQueue.Count);
_conn = conn(); _conn = conn();
_conn.Open(); _conn.Open();
} }
else else
{ {
Console.WriteLine("[DequeueSQLConn]取出一个SQLCount.Count>" + SQLPool.Count); MySqlConnection temp = null;
_conn = SQLPool.Dequeue(); while (_ConQueue.Count > 0)
{
Console.WriteLine("[DequeueSQLConn]取出一个SQLCount.Count>" + _ConQueue.Count);
temp = _ConQueue.Dequeue();
if (temp.State == System.Data.ConnectionState.Closed)
{
Console.WriteLine("[DequeueSQLConn]已经断开SQLCount.Count>" + _ConQueue.Count);
temp.Dispose();
temp = null;
continue;
} }
}
if (temp != null)
{
_conn = temp;
}
else
{
Console.WriteLine("[DequeueSQLConn]连接池全部已断开,重新创建连接");
_conn = conn();
_conn.Open();
}
}
_OutOfSQLPool.Add(_conn, new Haoyue_PoolTime _OutOfSQLPool.Add(_conn, new Haoyue_PoolTime
{ {
time = time(), time = time(),
FuncStr = FuncStr FuncStr = FuncStr
}); });
return _conn; return _conn;
} }
} }
@ -87,16 +109,17 @@ namespace AxibugEmuOnline.Web.Common
{ {
Console.WriteLine("出队遗漏的数据出现了!"); Console.WriteLine("出队遗漏的数据出现了!");
} }
if (SQLPool.Count > MaxLimit) if (_ConQueue.Count > MaxLimit)
{ {
Console.WriteLine("已经不需要回收了,多余了,SQLPool.Count>" + SQLPool.Count); Console.WriteLine("已经不需要回收了,多余了,SQLPool.Count>" + _ConQueue.Count);
BackConn.Close(); BackConn.Close();
BackConn.Dispose();
BackConn = null; BackConn = null;
} }
else else
{ {
SQLPool.Enqueue(BackConn); _ConQueue.Enqueue(BackConn);
Console.WriteLine("回收SQLPool.Count>" + SQLPool.Count); Console.WriteLine("回收SQLPool.Count>" + _ConQueue.Count);
} }
} }
} }
@ -119,15 +142,15 @@ namespace AxibugEmuOnline.Web.Common
{ {
_DicTimeOutSqlRunFunNum[o2.Value.FuncStr] = 1L; _DicTimeOutSqlRunFunNum[o2.Value.FuncStr] = 1L;
} }
if (SQLPool.Count > MaxLimit) if (_ConQueue.Count > MaxLimit)
{ {
Console.WriteLine("[超时回收]" + o2.Value.FuncStr + "已经不需要回收了,多余了,SQLPool.Count>" + SQLPool.Count); Console.WriteLine("[超时回收]" + o2.Value.FuncStr + "已经不需要回收了,多余了,SQLPool.Count>" + _ConQueue.Count);
o2.Key.Close(); o2.Key.Close();
} }
else else
{ {
Console.WriteLine("[超时回收]" + o2.Value.FuncStr + "回收SQLPool.Count>" + SQLPool.Count); Console.WriteLine("[超时回收]" + o2.Value.FuncStr + "回收SQLPool.Count>" + _ConQueue.Count);
SQLPool.Enqueue(o2.Key); _ConQueue.Enqueue(o2.Key);
} }
removeTemp.Add(o2.Key); removeTemp.Add(o2.Key);
} }
@ -148,7 +171,7 @@ namespace AxibugEmuOnline.Web.Common
Console.WriteLine("[超时回收]_OutOfSQLPool清理异常"); Console.WriteLine("[超时回收]_OutOfSQLPool清理异常");
} }
} }
Console.WriteLine("[超时回收]处理结束SQLPool.Count>" + SQLPool.Count); Console.WriteLine("[超时回收]处理结束SQLPool.Count>" + _ConQueue.Count);
} }
} }
public static long time() public static long time()

View File

@ -1,7 +1,9 @@
using AxibugEmuOnline.Web.Common; using AxibugEmuOnline.Web.Common;
using AxibugProtobuf;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using MySql.Data.MySqlClient; using MySql.Data.MySqlClient;
using Mysqlx.Crud; using Mysqlx.Crud;
using System.Reflection.PortableExecutable;
namespace AxibugEmuOnline.Web.Controllers namespace AxibugEmuOnline.Web.Controllers
{ {
@ -14,6 +16,27 @@ namespace AxibugEmuOnline.Web.Controllers
_logger = logger; _logger = logger;
} }
static bool TryDecrypToken(string tokenStr,out Protobuf_Token_Struct tokenData)
{
if (string.IsNullOrEmpty(tokenStr) || string.IsNullOrEmpty(tokenStr.Trim()))
{
tokenData = null;
return false;
}
try
{
byte[] encryptData = Convert.FromBase64String(tokenStr.Trim());
byte[] decryptData = AESHelper.Decrypt(encryptData);
tokenData = ProtoBufHelper.DeSerizlize<Protobuf_Token_Struct>(decryptData);
return true;
}
catch
{
tokenData = null;
return false;
}
}
[HttpGet] [HttpGet]
public JsonResult CheckStandInfo(int platform, string version) public JsonResult CheckStandInfo(int platform, string version)
{ {
@ -29,15 +52,21 @@ namespace AxibugEmuOnline.Web.Controllers
} }
[HttpGet] [HttpGet]
public JsonResult RomList(string SearchKey, int Ptype, int GType, int Page, int PageSize) public JsonResult RomList(string SearchKey, int Ptype, int GType, int Page, int PageSize,string Token)
{ {
long UID = 0;
if (TryDecrypToken(Token, out Protobuf_Token_Struct tokenData))
{
UID = tokenData.UID;
}
string searchPattern = $"%{SearchKey}%"; string searchPattern = $"%{SearchKey}%";
Resp_GameList resp = new Resp_GameList(); Resp_GameList resp = new Resp_GameList();
resp.gameList = new List<Resp_RomInfo>(); resp.gameList = new List<Resp_RomInfo>();
MySqlConnection conn = Haoyue_SQLPoolManager.DequeueSQLConn("RomList"); MySqlConnection conn = SQLPool.DequeueSQLConn("RomList");
{ {
string platformCond = ""; string platformCond = "";
if (GType > 0) if (GType > (int)RomPlatformType.Invalid && GType < (int)RomPlatformType.All)
{ {
platformCond = $" and PlatformType = '{Ptype}' "; platformCond = $" and PlatformType = '{Ptype}' ";
} }
@ -90,7 +119,7 @@ namespace AxibugEmuOnline.Web.Controllers
int orderIndex = Page * PageSize; int orderIndex = Page * PageSize;
while (reader.Read()) while (reader.Read())
{ {
resp.gameList.Add(new Resp_RomInfo() Resp_RomInfo data = new Resp_RomInfo()
{ {
orderid = orderIndex++, orderid = orderIndex++,
id = reader.GetInt32(0), id = reader.GetInt32(0),
@ -103,21 +132,133 @@ namespace AxibugEmuOnline.Web.Controllers
playcount = reader.GetInt32(7), playcount = reader.GetInt32(7),
stars = reader.GetInt32(8), stars = reader.GetInt32(8),
ptype = reader.GetInt32(9), ptype = reader.GetInt32(9),
}); };
if (UID > 0)
{
if (CheckIsRomStar(data.id, UID))
data.isStar = 1;
}
resp.gameList.Add(data);
} }
} }
} }
Haoyue_SQLPoolManager.EnqueueSQLConn(conn); SQLPool.EnqueueSQLConn(conn);
}
return new JsonResult(resp);
}
[HttpGet]
public JsonResult MarkList(string SearchKey, int Ptype, int GType, int Page, int PageSize, string Token)
{
long UID = 0;
if (TryDecrypToken(Token, out Protobuf_Token_Struct tokenData))
{
UID = tokenData.UID;
}
string searchPattern = $"%{SearchKey}%";
Resp_GameList resp = new Resp_GameList();
resp.gameList = new List<Resp_RomInfo>();
MySqlConnection conn = SQLPool.DequeueSQLConn("MarkList");
{
string platformCond = "";
if (GType > (int)RomPlatformType.Invalid && GType < (int)RomPlatformType.All)
{
platformCond = $" and romlist.PlatformType = '{Ptype}' ";
}
GameType SearchGType = (GameType)GType;
string GameTypeCond = "";
switch (SearchGType)
{
case GameType.NONE:
GameTypeCond = string.Empty;
break;
case GameType.ALLINONE:
GameTypeCond = $" and romlist.GameType = '合卡' ";
break;
default:
GameTypeCond = $" and romlist.GameType = '{SearchGType.ToString()}' ";
break;
}
string query = "SELECT count(romlist.id) from rom_stars LEFT JOIN romlist on romlist.Id = rom_stars.id where rom_stars.uid = ?uid and romlist.`Name` like ?searchPattern " + platformCond + GameTypeCond;
using (var command = new MySqlCommand(query, conn))
{
// 设置参数值
command.Parameters.AddWithValue("?uid", UID);
command.Parameters.AddWithValue("?searchPattern", searchPattern);
// 执行查询并处理结果
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
resp.resultAllCount = reader.GetInt32(0);
resp.page = Page;
resp.maxPage = (int)Math.Ceiling((float)resp.resultAllCount / PageSize);
}
}
}
string HotOrderBy = "ORDER BY playcount DESC, id ASC";
query = $"SELECT romlist.id,romlist.`Name`,romlist.GameType,romlist.Note,romlist.RomUrl,romlist.ImgUrl,romlist.`Hash`,romlist.`playcount`,romlist.`stars`,romlist.`PlatformType` from rom_stars LEFT JOIN romlist on romlist.Id = rom_stars.id where rom_stars.uid = ?uid and romlist.`Name` like ?searchPattern {platformCond} {GameTypeCond} {HotOrderBy} LIMIT ?offset, ?pageSize;";
using (var command = new MySqlCommand(query, conn))
{
// 设置参数值
command.Parameters.AddWithValue("?uid", UID);
command.Parameters.AddWithValue("?searchPattern", searchPattern);
command.Parameters.AddWithValue("?offset", Page * PageSize);
command.Parameters.AddWithValue("?pageSize", PageSize);
// 执行查询并处理结果
using (var reader = command.ExecuteReader())
{
int orderIndex = Page * PageSize;
while (reader.Read())
{
Resp_RomInfo data = new Resp_RomInfo()
{
orderid = orderIndex++,
id = reader.GetInt32(0),
romName = !reader.IsDBNull(1) ? reader.GetString(1) : string.Empty,
gType = !reader.IsDBNull(2) ? reader.GetString(2) : string.Empty,
desc = !reader.IsDBNull(3) ? reader.GetString(3) : string.Empty,
url = !reader.IsDBNull(4) ? reader.GetString(4) : string.Empty,
imgUrl = !reader.IsDBNull(5) ? reader.GetString(5) : string.Empty,
hash = !reader.IsDBNull(6) ? reader.GetString(6) : string.Empty,
playcount = reader.GetInt32(7),
stars = reader.GetInt32(8),
ptype = reader.GetInt32(9),
};
//毕竟都是已经收藏了的
data.isStar = 1;
resp.gameList.Add(data);
}
}
}
SQLPool.EnqueueSQLConn(conn);
} }
return new JsonResult(resp); return new JsonResult(resp);
} }
[HttpGet] [HttpGet]
public JsonResult RomInfo(int Ptype, int RomID) public JsonResult RomInfo(int Ptype, int RomID, string Token)
{ {
long UID = 0;
if (TryDecrypToken(Token, out Protobuf_Token_Struct tokenData))
{
UID = tokenData.UID;
}
string searchPattern = $"%{RomInfo}%"; string searchPattern = $"%{RomInfo}%";
Resp_RomInfo resp = new Resp_RomInfo(); Resp_RomInfo resp = new Resp_RomInfo();
MySqlConnection conn = Haoyue_SQLPoolManager.DequeueSQLConn("NesRomList"); MySqlConnection conn = SQLPool.DequeueSQLConn("NesRomList");
{ {
string query = $"SELECT id,`Name`,GameType,Note,RomUrl,ImgUrl,`Hash`,`playcount`,`stars`,`PlatformType` FROM romlist where id = ?romid;"; string query = $"SELECT id,`Name`,GameType,Note,RomUrl,ImgUrl,`Hash`,`playcount`,`stars`,`PlatformType` FROM romlist where id = ?romid;";
using (var command = new MySqlCommand(query, conn)) using (var command = new MySqlCommand(query, conn))
@ -142,8 +283,15 @@ namespace AxibugEmuOnline.Web.Controllers
} }
} }
} }
Haoyue_SQLPoolManager.EnqueueSQLConn(conn); SQLPool.EnqueueSQLConn(conn);
} }
if (UID > 0)
{
if (CheckIsRomStar(resp.id, UID))
resp.isStar = 1;
}
return new JsonResult(resp); return new JsonResult(resp);
} }
@ -170,6 +318,37 @@ namespace AxibugEmuOnline.Web.Controllers
ALLINONE, ALLINONE,
} }
public bool CheckIsRomStar(int RomId, long uid)
{
bool bhad = false;
MySqlConnection conn = SQLPool.DequeueSQLConn("CheckIsRomStart");
try
{
string query = $"SELECT count(0) from rom_stars where uid = ?uid and = ?romid";
using (var command = new MySqlCommand(query, conn))
{
// 设置参数值
command.Parameters.AddWithValue("?RomID", RomId);
command.Parameters.AddWithValue("?uid", uid);
// 执行查询并处理结果
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
bhad = reader.GetInt32(0) > 0;
}
}
}
}
catch (Exception e)
{
//AppSrv.g_Log.Error(e);
}
SQLPool.EnqueueSQLConn(conn);
return bhad;
}
class Resp_CheckStandInfo class Resp_CheckStandInfo
{ {
public int needUpdateClient { get; set; } public int needUpdateClient { get; set; }
@ -201,6 +380,8 @@ namespace AxibugEmuOnline.Web.Controllers
public string hash { get; set; } public string hash { get; set; }
public int stars { get; set; } public int stars { get; set; }
public int playcount { get; set; } public int playcount { get; set; }
public int isStar { get; set; }
} }
} }
} }

View File

@ -7,7 +7,8 @@ namespace AxibugEmuOnline.Web
public static void Main(string[] args) public static void Main(string[] args)
{ {
Config.LoadConfig(); Config.LoadConfig();
Haoyue_SQLPoolManager.InitConnMgr(); AESHelper.LoadKeyIVCfg(Config.cfg.AesKey, Config.cfg.AesIv);
SQLPool.InitConnMgr();
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);

File diff suppressed because it is too large Load Diff

View File

@ -210,6 +210,13 @@ message Protobuf_Login_RESP
} }
//Token结构token
message Protobuf_Token_Struct
{
int64 UID = 1;
int64 TokenGenDate = 2;
int64 Seed = 3;
}
//线 //线
message Protobuf_UserList message Protobuf_UserList
@ -426,10 +433,12 @@ message Protobuf_Room_Get_Screen_RESP
message Protobuf_Game_Mark message Protobuf_Game_Mark
{ {
int32 RomID = 1;//RomID int32 RomID = 1;//RomID
int32 state = 2;//[0] [1] int32 motion = 2;//[0][1]
} }
message Protobuf_Game_Mark_RESP message Protobuf_Game_Mark_RESP
{ {
int32 RomID = 1;//RomID int32 RomID = 1;//RomID
int32 IsStar = 2;// [0][1]
int32 stars = 3;//
} }