server finish nlog

This commit is contained in:
2025-04-10 21:53:21 +08:00
parent 143d6c634b
commit c9660633f0
8 changed files with 247 additions and 45 deletions

View File

@@ -3,26 +3,36 @@ using System.Net.Sockets;
using System.Text;
using DotNext;
using DotNext.Threading;
using Newtonsoft.Json;
/// <summary> UDP接受数据包格式 </summary>
public struct UDPData
public class UDPData
{
/// <summary>
/// 接受到的时间
/// </summary>
public DateTime datetime;
public DateTime DateTime { get; set; }
/// <summary>
/// 发送来源的IP地址
/// </summary>
public string addr;
public string Address { get; set; }
/// <summary>
/// 发送来源的端口号
/// </summary>
public int port;
public int Port { get; set; }
/// <summary>
/// 接受到的数据
/// </summary>
public byte[] data;
public byte[] Data { get; set; }
/// <summary>
/// 将UDP Data 转化为Json 格式字符串
/// </summary>
/// <returns>json字符串</returns>
public override string ToString()
{
return JsonConvert.SerializeObject(this);
}
}
/// <summary>
@@ -30,6 +40,8 @@ public struct UDPData
/// </summary>
public class UDPServer
{
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
private int listenPort;
private UdpClient listener;
private IPEndPoint groupEP;
@@ -142,6 +154,38 @@ public class UDPServer
}
}
public async ValueTask<Optional<List<UDPData>>> GetDataArrayAsync(string ipAddr, int timeout = 1000)
{
List<UDPData>? data = null;
var startTime = DateTime.Now;
var isTimeout = false;
var timeleft = TimeSpan.FromMilliseconds(timeout);
while (!isTimeout)
{
using (await udpDataLock.AcquireReadLockAsync(timeleft))
{
if (udpData.ContainsKey(ipAddr))
{
data = udpData[ipAddr];
}
}
timeleft = DateTime.Now.Subtract(startTime);
isTimeout = timeleft >= TimeSpan.FromMilliseconds(timeout);
}
if (data == null)
{
return Optional.None<List<UDPData>>();
}
else
{
return Optional.Some((List<UDPData>)data);
}
}
private void ReceiveHandler(IAsyncResult res)
{
var remoteEP = new IPEndPoint(IPAddress.Any, listenPort);
@@ -150,33 +194,42 @@ public class UDPServer
// Handle RemoteEP
string remoteStr = "Unknown";
if (remoteEP is not null)
using (udpDataLock.AcquireWriteLock())
{
var remoteAddress = remoteEP.Address.ToString();
var remotePort = remoteEP.Port;
// Record UDP Receive Data
if (udpData.ContainsKey(remoteAddress))
if (remoteEP is not null)
{
var listData = udpData[remoteAddress];
listData.Add(new UDPData()
var remoteAddress = remoteEP.Address.ToString();
var remotePort = remoteEP.Port;
// Record UDP Receive Data
if (udpData.ContainsKey(remoteAddress))
{
addr = remoteAddress,
port = remotePort,
data = bytes,
datetime = nowtime,
});
var listData = udpData[remoteAddress];
listData.Add(new UDPData()
{
Address = remoteAddress,
Port = remotePort,
Data = bytes,
DateTime = nowtime,
});
logger.Trace("Receive data from old client");
}
else
{
udpData.Add(remoteAddress, new List<UDPData>([new UDPData(){
Address = remoteAddress,
Port = remotePort,
Data = bytes,
DateTime = nowtime,
}]));
logger.Trace("Receive data from new client");
}
remoteStr = $"{remoteAddress}:{remotePort}";
}
else
{
udpData.Add(remoteAddress, new List<UDPData>([new UDPData(){
addr = remoteAddress,
port = remotePort,
data = bytes,
datetime = nowtime,
}]));
logger.Warn("Receive data from unknown client");
}
remoteStr = $"{remoteAddress}:{remotePort}";
}
// Handle Package
@@ -212,14 +265,35 @@ public class UDPServer
recvData = Encoding.ASCII.GetString(bytes, 0, bytes.Length);
}
Console.WriteLine($"Receive Data from {remoteStr} at {nowtime.ToString()}:");
Console.WriteLine($"Original Data: {BitConverter.ToString(bytes).Replace("-", " ")}");
if (recvData.Length != 0) Console.WriteLine(recvData);
Console.WriteLine();
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);
}
/// <summary>
/// 将所有数据输出到log中
/// </summary>
/// <returns> void </returns>
public void RecordAllData()
{
using (udpDataLock.AcquireReadLock())
{
logger.Debug("Ready Data:");
foreach (var ip in udpData)
{
foreach (var data in ip.Value)
{
logger.Debug(data.ToString());
}
}
}
}
/// <summary>
/// Start UDP Server
/// </summary>