finish receive udp data handle function

This commit is contained in:
2025-04-03 17:21:22 +08:00
parent 2af0986d67
commit 342a5a2436
2 changed files with 110 additions and 8 deletions

View File

@@ -1,6 +1,7 @@
using System.Net;
using System.Net.Sockets;
using System.Text;
using DotNext;
public struct UDPData
{
@@ -18,7 +19,8 @@ public class UDPServer
private int listenPort;
private UdpClient listener;
private IPEndPoint groupEP;
private Dictionary<string, UDPData> udpData = new Dictionary<string, UDPData>();
private Dictionary<string, List<UDPData>> udpData = new Dictionary<string, List<UDPData>>();
private Mutex mutUdpData = new Mutex();
/// <summary>
/// Construct a udp server with fixed port
@@ -44,6 +46,84 @@ public class UDPServer
}
}
/// <summary>
/// Find UDP Receive Data According to ip address
/// </summary>
/// <param name="ipAddr"> IP Address</param>
/// <returns>UDP Data</returns>
public Optional<UDPData> FindData(string ipAddr)
{
UDPData? data = null;
try
{
var isOverTime = !mutUdpData.WaitOne(1000);
if (isOverTime) return Optional.None<UDPData>();
// Get
var listData = udpData[ipAddr];
data = listData[0];
// Delete
listData.RemoveAt(0);
}
catch
{
data = null;
}
finally
{
mutUdpData.ReleaseMutex();
}
// Return
if (data is null)
{
return Optional.None<UDPData>();
}
else
{
return Optional.Some((UDPData)data);
}
}
/// <summary>
/// Find UDP Receive Data Async
/// </summary>
/// <param name="ipAddr">[TODO:parameter]</param>
/// <param name="timeout">[TODO:parameter]</param>
/// <returns>[TODO:return]</returns>
public async ValueTask<Optional<UDPData>> FindDataAsync(string ipAddr, int timeout = 1000)
{
var time = 0;
UDPData? data = null;
while (time < timeout)
{
await Task.Delay(1);
try
{
var isOverTime = !mutUdpData.WaitOne(timeout - time);
if (isOverTime) break;
// Get
var listData = udpData[ipAddr];
data = listData[0];
// Delete
listData.RemoveAt(0);
}
catch
{
data = null;
}
finally
{
mutUdpData.ReleaseMutex();
}
if (data is null) continue;
else break;
}
if ((time >= timeout) || (data is null)) { return Optional.None<UDPData>(); }
else { return Optional.Some((UDPData)data); }
}
private void ReceiveHandler(IAsyncResult res)
{
var remoteEP = new IPEndPoint(IPAddress.Any, listenPort);
@@ -57,13 +137,27 @@ public class UDPServer
var remoteAddress = remoteEP.Address.ToString();
var remotePort = remoteEP.Port;
// Record UDP Receive Data
udpData.Add(remoteAddress, new UDPData()
if (udpData.ContainsKey(remoteAddress))
{
addr = remoteAddress,
port = remotePort,
data = bytes,
datetime = nowtime,
});
var listData = udpData[remoteAddress];
listData.Add(new UDPData()
{
addr = remoteAddress,
port = remotePort,
data = bytes,
datetime = nowtime,
});
}
else
{
udpData.Add(remoteAddress, new List<UDPData>([new UDPData(){
addr = remoteAddress,
port = remotePort,
data = bytes,
datetime = nowtime,
}]));
}
remoteStr = $"{remoteAddress}:{remotePort}";
}
else