init csharp server

This commit is contained in:
2025-03-29 19:02:18 +08:00
parent cddf92e432
commit 351aad8300
12 changed files with 216 additions and 5 deletions

63
server/src/UdpServer.cs Normal file
View File

@@ -0,0 +1,63 @@
using System.Net;
using System.Net.Sockets;
using System.Text;
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);
Console.WriteLine($"Received broadcast from {groupEP} :");
Console.WriteLine($" {Encoding.ASCII.GetString(bytes, 0, bytes.Length)}");
}
}
catch (SocketException e)
{
Console.WriteLine(e);
}
finally
{
listener.Close();
}
}
public void Start()
{
isRunning = true;
thrd.Start();
}
public void Stop()
{
isRunning = false;
thrd.Join();
}
}