SafeDispatch/SafeMobileLIB_DLL/UdpServer.cs
2024-02-22 18:43:59 +02:00

100 lines
2.6 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Net;
namespace SafeMobileLib
{
public class UdpServer
{
private UdpClient udpClient;
private Thread listenThread;
private int port;
private bool working = false;
private IPEndPoint sourceEP;
public UdpServer(int _port)
{
udpClient = null;
port = _port;
sourceEP = new IPEndPoint(IPAddress.Any, 0);
}
public void Start()
{
Console.WriteLine("Starting UDP server on port:"+port);
working = true;
udpClient = new UdpClient(port);
listenThread = new Thread(new ThreadStart(Listen));
listenThread.Start();
}
public void Stop()
{
Console.WriteLine("Stoping UDP server");
working = false;
if (udpClient != null)
{
udpClient.Close();
udpClient = null;
}
if (listenThread != null)
{
listenThread.Abort();
listenThread = null;
}
}
private void Listen()
{
byte[] data = new byte[65507];
while (working)
{
try
{
data = udpClient.Receive(ref sourceEP);
Console.WriteLine("Data recv from :" + sourceEP.Address.ToString());
if (this.OnNewDataRecv != null)
this.OnNewDataRecv(data, data.Length, sourceEP.Address);
if (this.OnNewDataEndPointRecv != null)
this.OnNewDataEndPointRecv(data, data.Length, sourceEP);
}
catch (Exception ex)
{
Console.WriteLine("ERROR UDPserver recv \n"+ ex.ToString());
}
}
}
public delegate void dataRecvDel(byte[] data, int dataLen, IPAddress ip);
public event dataRecvDel OnNewDataRecv;
public delegate void dataRecvEndPointDel(byte[] data, int dataLen, IPEndPoint ip);
public event dataRecvEndPointDel OnNewDataEndPointRecv;
public void Send(byte[] data, int dataLen, IPEndPoint EP)
{
if (udpClient != null)
{
udpClient.Send(data, dataLen, EP);
}
else
{
Console.WriteLine("ERRROR sending on UDP to:" + EP.Address.ToString());
}
}
}
}