rewrite udp server handler, change router and protocol

This commit is contained in:
2025-04-14 21:31:50 +08:00
parent 5fa4860bfb
commit ae34cf6436
5 changed files with 289 additions and 78 deletions

View File

@@ -1,6 +1,7 @@
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using DotNext;
using DotNext.Threading;
using Newtonsoft.Json;
@@ -42,6 +43,9 @@ public class UDPData
/// <summary>
/// UDP Server
/// </summary>
/// <summary>
/// UDP 服务器
/// </summary>
public class UDPServer
{
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
@@ -52,6 +56,11 @@ public class UDPServer
private Dictionary<string, List<UDPData>> udpData = new Dictionary<string, List<UDPData>>();
private AsyncReaderWriterLock udpDataLock = new AsyncReaderWriterLock(1);
/// <summary>
/// 是否开启Debug模式
/// </summary>
public bool EnableDebugMode { get; set; }
/// <summary>
/// Construct a udp server with fixed port
/// </summary>
@@ -256,52 +265,133 @@ public class UDPServer
{
var remoteEP = new IPEndPoint(IPAddress.Any, listenPort);
byte[] bytes = listener.EndReceive(res, ref remoteEP);
var nowtime = DateTime.Now;
// Handle RemoteEP
string remoteStr = "Unknown";
using (udpDataLock.AcquireWriteLock())
if (remoteEP is null)
{
if (remoteEP is not null)
{
var remoteAddress = remoteEP.Address.ToString();
var remotePort = remoteEP.Port;
// Record UDP Receive Data
if (udpData.ContainsKey(remoteAddress))
{
var listData = udpData[remoteAddress];
listData.Add(new UDPData()
{
Address = remoteAddress,
Port = remotePort,
Data = bytes,
DateTime = nowtime,
HasRead = false,
});
logger.Trace("Receive data from old client");
}
else
{
udpData.Add(remoteAddress, new List<UDPData>([new UDPData()
{
Address = remoteAddress,
Port = remotePort,
Data = bytes,
DateTime = nowtime,
HasRead = false,
}]));
logger.Trace("Receive data from new client");
}
logger.Debug($"Receive Data from Unknown at {DateTime.Now.ToString()}:");
logger.Debug($" Original Data : {BitConverter.ToString(bytes).Replace("-", " ")}");
goto BEGIN_RECEIVE;
}
remoteStr = $"{remoteAddress}:{remotePort}";
// If enable Debug mode, exec Debug handler
if (EnableDebugMode)
{
DebugHandler(new IPEndPoint(IPAddress.Parse("127.0.0.1"), this.listenPort), bytes);
}
else
{
// Handle Package
PrintData(RecordUDPData(bytes, remoteEP));
}
BEGIN_RECEIVE:
listener.BeginReceive(new AsyncCallback(ReceiveHandler), null);
}
private void DebugHandler(IPEndPoint ep, byte[] bytes)
{
// Print Receive Data
var data = new UDPData()
{
Address = ep.Address.ToString(),
Port = ep.Port,
Data = bytes,
DateTime = DateTime.Now,
HasRead = false,
};
PrintData(data);
// Handle Pack Type
var sign = bytes[0];
if (sign == (byte)WebProtocol.PackSign.SendAddr)
{
var resData = WebProtocol.SendAddrPackage.FromBytes(bytes);
if (!resData.IsSuccessful)
{
logger.Warn("DebugHandler: Convert to SendAddrPackage failed");
return;
}
if (resData.Value.Options.IsWrite)
{
var pack = new WebProtocol.RecvRespPackage(resData.Value.Options.CommandID, true);
SendBytes(ep, pack.ToBytes());
}
else
{
logger.Warn("Receive data from unknown client");
var pack = new WebProtocol.RecvDataPackage(resData.Value.Options.CommandID, true, [0, 0, 0, 0]);
SendBytes(ep, pack.ToBytes());
}
}
else if (sign == (byte)WebProtocol.PackSign.SendData)
{
}
else
{
SendString(ep, "DebugHandler: Receive Data");
}
// Handle Package
logger.Trace("DebugHandler: send pack successfully");
}
private bool SendBytes(IPEndPoint endPoint, byte[] buf)
{
var sendLen = listener.Send(buf, endPoint);
if (sendLen == buf.Length) { return true; }
else { return false; }
}
private bool SendString(IPEndPoint endPoint, string text)
{
byte[] buf = Encoding.ASCII.GetBytes(text);
var sendLen = listener.Send(buf, endPoint);
if (sendLen == buf.Length) { return true; }
else { return false; }
}
private UDPData RecordUDPData(byte[] bytes, IPEndPoint remoteEP)
{
using (udpDataLock.AcquireWriteLock())
{
var remoteAddress = remoteEP.Address.ToString();
var remotePort = remoteEP.Port;
var data = new UDPData()
{
Address = remoteAddress,
Port = remotePort,
Data = bytes,
DateTime = DateTime.Now,
HasRead = false,
};
// Record UDP Receive Data
if (udpData.ContainsKey(remoteAddress))
{
var listData = udpData[remoteAddress];
listData.Add(data);
logger.Trace("Receive data from old client");
}
else
{
udpData.Add(remoteAddress, new List<UDPData>([data]));
logger.Trace("Receive data from new client");
}
return data;
}
}
/// <summary>
/// 输出UDP Data到log中
/// </summary>
/// <param name="data">UDP数据</param>
public void PrintData(UDPData data)
{
var bytes = data.Data;
var sign = bytes[0];
string recvData = "";
if (sign == (byte)WebProtocol.PackSign.SendAddr)
@@ -334,20 +424,16 @@ public class UDPServer
recvData = Encoding.ASCII.GetString(bytes, 0, bytes.Length);
}
logger.Debug($"Receive Data from {remoteStr} at {nowtime.ToString()}:");
logger.Debug($"Original Data: {BitConverter.ToString(bytes).Replace("-", " ")}");
if (recvData.Length != 0) logger.Debug(recvData);
// RecordAllData();
listener.BeginReceive(new AsyncCallback(ReceiveHandler), null);
logger.Debug($"Receive Data from {data.Address}:{data.Port} at {data.DateTime.ToString()}:");
logger.Debug($" Original Data : {BitConverter.ToString(bytes).Replace("-", " ")}");
if (recvData.Length != 0) logger.Debug($" Decoded Data : {recvData}");
}
/// <summary>
/// 将所有数据输出到log中
/// </summary>
/// <returns> void </returns>
public void RecordAllData()
public void PrintAllData()
{
using (udpDataLock.AcquireReadLock())
{