110,545
社区成员
发帖
与我相关
我的任务
分享
public class UDPSingleListener : IDisposable
{
Thread thread;
bool IsThreadRunning = false;
int listenPort = 999;
IPAddress ip = IPAddress.Parse("127.0.0.1");
UdpClient listener = null;
public UDPSingleListener(string ipaddress, int port)
{
listenPort = port;
ip = IPAddress.Parse(ipaddress);
}
public void Dispose()
{
StopListen();
ip = null;
listener = null;
}
public void StartListen()
{
IsThreadRunning = true;
thread = new Thread(new ThreadStart(Listener));
thread.Start();
}
public void StopListen()
{
IsThreadRunning = false;
try
{
if (listener != null)
{
listener.Close();
listener = null;
}
}
catch
{
}
}
public delegate void ReceiveData(byte[] bytes, string ipaddress, int port);
public event ReceiveData OnReceiveData;
void Listener()
{
try
{
listener = new UdpClient(listenPort, AddressFamily.InterNetwork);
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, 0);
while (IsThreadRunning)
{
byte[] bytes = listener.Receive(ref groupEP);
if (OnReceiveData != null)
{
OnReceiveData(bytes, groupEP.Address.ToString(), groupEP.Port);
}
}
}
catch //(Exception err)
{
//MessageBox.Show(err.ToString());
//throw new Exception(err.ToString ());
}
finally
{
}
}
}