using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.ComponentModel;
namespace IM.Controls
{
public class ClsUDPSrv
{
public ClsUDPSrv()
{
IsDispose = false;
}
public UdpClient UDP_Srv = new UdpClIEnt();
public static int UDPServer_Port = 2007;
privateint UDPClIEnt_Port;
private Thread td_Udp;
private IPEndPoint IPEP_Srv = new IPEndPoint(IPAddress.Any, 0);
public delegate void DataControlEventHandler(byte[] Data, System.Net.IPAddress Ip, int Port);
public event DataControlEventHandler DataControl;
public delegate void Udp_ErrorEventHandler(string Error);
public event Udp_ErrorEventHandler Udp_Error;
public bool IsDispose = false;
public void Listen(int Port)
{
try
{
IsDispose = false;
UDPClIEnt_Port = Port;
UDP_Srv = new UdpClIEnt(Port);
td_Udp = new Thread(new ThreadStart$False$
(UDPDataControl));
td_Udp.IsBackground = true;
td_Udp.Start();
}
catch (Exception ex)
{
if (Udp_Error != null)
Udp_Error(ex.ToString());
}
}
private void ReceiveDataControl()
{
while (!IsDispose)
{
try
{
byte[] Data = UDP_Srv.Receive(ref IPEP_Srv);
if (DataControl != null)
DataControl(Data, IPEP_Srv.Address, IPEP_Srv.Port);
Thread.Sleep(0);
}
catch (Exception ex)
{
if (Udp_Error != null)
Udp_Error(ex.ToString());
}
}
}
public void SendData(System.Net.IPAddress Host, int Port, byte[] Data)
{
try
{
IPEndPoint server = new IPEndPoint(Host, Port);
UDP_Srv.Send(Data, Data.Length, server);
}
catch (Exception ex)
{
if (Udp_Error != null)
Udp_Error(ex.ToString());
}
}
public void Dispose()
{
Thread.Sleep(30);
try
{
IsDispose = true;
UDP_Srv.Close();
td_Udp.Abort();
}
catch (Exception ex)
{
if (Udp_Error != null)
Udp_Error(ex.ToString());
}
}