异步服务端

This commit is contained in:
Longfeng Qin 2024-09-11 16:33:10 +08:00
parent 68032fdc86
commit 802b810c2c
4 changed files with 90 additions and 39 deletions

View File

@ -137,7 +137,7 @@ namespace PSO2SERVER.Database
}
}
public bool TestDatabaseConnection()
public bool TestDatabaseConnection2()
{
try
{
@ -152,7 +152,26 @@ namespace PSO2SERVER.Database
}
catch (Exception ex)
{
Logger.WriteException("[DBT] 数据库连接异常", ex);
Logger.WriteException("数据库连接异常", ex);
return false;
}
}
public bool TestDatabaseConnection()
{
try
{
using (var context = new ServerEf())
{
context.Database.Initialize(force: false);
Logger.WriteInternal("[DBT] 数据库连接成功。");
return true;
}
}
catch (Exception ex)
{
Logger.WriteException("数据库连接异常", ex);
return false;
}
}

View File

@ -32,6 +32,12 @@ namespace PSO2SERVER.Packets.Handlers
var info = string.Format("[<--] 接收到的数据 (hex): ");
Logger.WriteHex(info, cryptedBlob);
// Convert cryptedBlob to a hexadecimal string
var hexString = BitConverter.ToString(cryptedBlob).Replace("-", "");
// Save the hexadecimal string to a text file
File.WriteAllText("cryptedBlob.txt", hexString);
// FIXME
if (Client.RsaCsp == null)
{

View File

@ -7,6 +7,7 @@ using System.Security.Cryptography;
using PSO2SERVER.Database;
using PSO2SERVER.Packets.Handlers;
using System.Threading.Tasks;
namespace PSO2SERVER
{
@ -122,32 +123,51 @@ namespace PSO2SERVER
Thread.Sleep(1000);
//System.Data.Entity.Database.SetInitializer(new System.Data.Entity.DropCreateDatabaseIfModelChanges<ServerEf>());
Instance = new ServerApp();
Instance.Start();
_ = Instance.StartAsync();
}
public void Start()
public async Task StartAsync()
{
Server = new Server();
Config.Load();
PacketHandlers.LoadPacketHandlers();
Logger.WriteInternal("[DBC] 载入数据库...");
using (var db = new ServerEf())
{
db.TestDatabaseConnection();
db.SetupDB();
}
for (var i = 0; i < 10; i++)
QueryServers.Add(new QueryServer(QueryMode.ShipList, 12099 + (100 * i)));
await InitializeConfigurationAsync();
await InitializeDatabaseAsync();
InitializeQueryServers(); // Assuming this is synchronous
Logger.WriteInternal("服务器启动完成 " + DateTime.Now);
Server.Run();
}
private async Task InitializeConfigurationAsync()
{
await Task.Run(() =>
{
Config.Load();
PacketHandlers.LoadPacketHandlers();
});
}
private async Task InitializeDatabaseAsync()
{
Logger.WriteInternal("[DBC] 载入数据库...");
await Task.Run(() =>
{
using (var db = new ServerEf())
{
db.TestDatabaseConnection();
db.SetupDB();
}
});
}
private void InitializeQueryServers()
{
for (var i = 0; i < 10; i++)
{
QueryServers.Add(new QueryServer(QueryMode.ShipList, 12099 + (100 * i)));
}
}
private static void Exit(object sender, EventArgs e)
{
// Save the configuration

View File

@ -8,6 +8,7 @@ using System.Threading;
using PSO2SERVER.Models;
using PSO2SERVER.Packets;
using System.Threading.Tasks;
namespace PSO2SERVER
{
@ -19,9 +20,7 @@ namespace PSO2SERVER
public class QueryServer
{
private delegate void OnConnection(Socket server);
public static List<Thread> RunningServers = new List<Thread>();
public static List<Task> RunningServers = new List<Task>();
private readonly QueryMode _mode;
private readonly int _port;
@ -30,25 +29,24 @@ namespace PSO2SERVER
{
_mode = mode;
_port = port;
var queryThread = new Thread(Run);
queryThread.Start();
RunningServers.Add(queryThread);
var queryTask = Task.Run(() => RunAsync());
RunningServers.Add(queryTask);
Logger.WriteInternal("[QSP] 开始监听端口 " + port);
}
private void Run()
private async Task RunAsync()
{
OnConnection c;
Func<Socket, Task> connectionHandler;
switch (_mode)
{
default:
c = DoShipList;
break;
case QueryMode.Block:
c = DoBlockBalance;
connectionHandler = DoBlockBalanceAsync;
break;
case QueryMode.ShipList:
c = DoShipList;
connectionHandler = DoShipListAsync;
break;
default:
connectionHandler = DoShipListAsync;
break;
}
@ -59,14 +57,15 @@ namespace PSO2SERVER
var ep = new IPEndPoint(IPAddress.Any, _port);
serverSocket.Bind(ep); // TODO: Custom bind address.
serverSocket.Listen(5);
while (true)
{
var newConnection = serverSocket.Accept();
c(newConnection);
var newConnection = await Task.Factory.FromAsync(serverSocket.BeginAccept, serverSocket.EndAccept, null);
_ = connectionHandler(newConnection); // Fire-and-forget pattern for handling connections
}
}
private void DoShipList(Socket socket)
private async Task DoShipListAsync(Socket socket)
{
var writer = new PacketWriter();
var entries = new List<ShipEntry>();
@ -92,12 +91,15 @@ namespace PSO2SERVER
writer.Write((Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds);
writer.Write(1);
socket.Send(writer.ToArray());
var buffer = writer.ToArray();
await Task.Factory.FromAsync(
(cb, state) => socket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, cb, state),
socket.EndSend,
null);
socket.Close();
}
private void DoBlockBalance(Socket socket)
private async Task DoBlockBalanceAsync(Socket socket)
{
var writer = new PacketWriter();
writer.WriteStruct(new PacketHeader(0x90, 0x11, 0x2C, 0x0, 0x0));
@ -106,7 +108,11 @@ namespace PSO2SERVER
writer.Write((UInt16)12205);
writer.Write(new byte[0x90 - 0x6A]);
socket.Send(writer.ToArray());
var buffer = writer.ToArray();
await Task.Factory.FromAsync(
(cb, state) => socket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, cb, state),
socket.EndSend,
null);
socket.Close();
}
}