finish web test api

This commit is contained in:
2025-03-31 20:24:26 +08:00
parent f455af3589
commit 0da5b85173
10 changed files with 392 additions and 59 deletions

View File

@@ -7,57 +7,87 @@ public class UDPServer
private int listenPort;
private UdpClient listener;
private IPEndPoint groupEP;
private Thread thrd;
private bool isRunning;
public UDPServer(int port)
{
// Construction
listenPort = port;
listener = new UdpClient(listenPort);
groupEP = new IPEndPoint(IPAddress.Any, listenPort);
// New Thread
var thrdStart = new ThreadStart(ReceiveHandler);
thrd = new Thread(thrdStart);
}
private void ReceiveHandler()
{
try
{
while (isRunning)
{
byte[] bytes = listener.Receive(ref groupEP);
listener = new UdpClient(listenPort);
groupEP = new IPEndPoint(IPAddress.Any, listenPort);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
throw new ArgumentException(
$"Not currect port num: {port}",
nameof(port)
);
}
}
Console.WriteLine($"Received broadcast from {groupEP} :");
Console.WriteLine($" {Encoding.ASCII.GetString(bytes, 0, bytes.Length)}");
}
}
catch (SocketException e)
private void ReceiveHandler(IAsyncResult res)
{
var remoteEP = new IPEndPoint(IPAddress.Any, listenPort);
byte[] bytes = listener.EndReceive(res, ref remoteEP);
var sign = bytes[0];
string recvData;
if (sign == (byte)WebProtocol.PackSign.SendAddr)
{
Console.WriteLine(e);
var resData = WebProtocol.SendAddrPackage.FromBytes(bytes);
if (resData.IsSuccessful)
recvData = resData.Value.ToString();
else
recvData = resData.Error.ToString();
}
finally
else if (sign == (byte)WebProtocol.PackSign.SendData)
{
listener.Close();
recvData = "";
}
else if (sign == (byte)WebProtocol.PackSign.RecvData)
{
recvData = "";
}
else if (sign == (byte)WebProtocol.PackSign.RecvResp)
{
recvData = "";
}
else
{
recvData = Encoding.ASCII.GetString(bytes, 0, bytes.Length);
}
string remoteStr = (remoteEP is null) ? "Unknown" : $"{remoteEP.Address.ToString()}:{remoteEP.Port.ToString()}";
Console.WriteLine($"Receive Data from {remoteStr} at {DateTime.Now.ToString()}:");
Console.WriteLine($"Original Data: {BitConverter.ToString(bytes).Replace("-", " ")}");
if (recvData.Length != 0) Console.WriteLine(recvData);
Console.WriteLine();
listener.BeginReceive(new AsyncCallback(ReceiveHandler), null);
}
public void Start()
{
isRunning = true;
thrd.Start();
try
{
listener.BeginReceive(new AsyncCallback(ReceiveHandler), null);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
finally
{
}
}
public void Stop()
{
isRunning = false;
thrd.Join();
listener.Close();
}
}