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

View File

View File

@@ -0,0 +1,41 @@
using System.Net;
using System.Net.Sockets;
using System.Text;
class UDPClientPool
{
private static IPAddress localhost = IPAddress.Parse("127.0.0.1");
public UDPClientPool()
{
}
public static void SendLocalHost(int port, string[] stringArray)
{
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
byte[] sendbuf = Encoding.ASCII.GetBytes(stringArray[0]);
IPEndPoint ep = new IPEndPoint(localhost, port);
socket.SendTo(sendbuf, ep);
}
public static void CycleSendLocalHost(int times, int sleepMilliSeconds, int port, string[] stringArray)
{
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
byte[] sendbuf = Encoding.ASCII.GetBytes(stringArray[0]);
IPEndPoint ep = new IPEndPoint(localhost, port);
while (times-- >= 0)
{
socket.SendTo(sendbuf, ep);
Thread.Sleep(sleepMilliSeconds);
}
}
public void Start()
{
}
}

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();
}
}