init csharp server
This commit is contained in:
63
server/src/UdpServer.cs
Normal file
63
server/src/UdpServer.cs
Normal 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();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user