110,534
社区成员
发帖
与我相关
我的任务
分享
public partial class UDPSocket : Component
{
private IPEndPoint ServerEndPoint = null; //定义网络端点
private UdpClient UDP_Server = new UdpClient(); //创建网络服务,即UDP的Socket
private Thread thdUdp; //创建线程
public delegate void DataArriveEventHandler(byte[] Data, IPAddress IP, int port); //定义数据到达托管事件
public event DataArriveEventHandler DataArrival; //通过托管,在空间中定义一个事件
private string localHost = "127.0.0.1"; //定义本机地址
[Browsable(true), Category("Local"), Description("本地ip地址")] //在窗口设置本地ip地址
public string LocalHost
{
get { return localHost; }
set { localHost = value; }
}
private int localPort = 11000;
[Browsable(true), Category("Local"), Description("本地端口号")] //在属性窗口显示本地端口号
public int LocalPort
{
get { return localPort; }
set { localPort = value; }
}
private bool active = false;
[Browsable(true), Category("Local"), Description("激活监听")] //在属性窗口显示激活监听属性
public bool Active
{
get { return active; }
set
{
active = value;
if (active)
{
OpenSocket(); //打开监听
}
else
{
CloseSocket(); //关闭监听
}
}
}
public UDPSocket() //构造函数
{
InitializeComponent();
}
public UDPSocket(IContainer container) //构造函数
{
container.Add(this);
InitializeComponent();
}
protected void Listener() //监听
{
ServerEndPoint = new IPEndPoint(IPAddress.Any, localPort); //创建服务器地址
if (UDP_Server != null)
UDP_Server.Close();
UDP_Server = new UdpClient(localPort);//创建新的端口号
UDP_Server.Client.ReceiveBufferSize = 1000000000;//接收缓冲区大小
UDP_Server.Client.SendBufferSize = 1000000000;//发送缓冲区大小
try
{
thdUdp = new Thread(new ThreadStart(GetUDPData));
thdUdp.Start();//执行当前线程
}
catch (Exception e)
{
MessageBox.Show(e.Message);//显示线程错误信息
//throw e;
}
}
private void GetUDPData()//获取当前接收的消息
{
while (active)
{
try
{
byte[] Data = UDP_Server.Receive(ref ServerEndPoint);
if (DataArrival != null)
{
DataArrival(Data, ServerEndPoint.Address, ServerEndPoint.Port);
}
Thread.Sleep(0);
}
catch
{
//throw e;
}
}
}
private void CallBackMethod(IAsyncResult ar)
{
//从异步状态ar.AsyncState中,获取委托对象
DataArriveEventHandler dn = (DataArriveEventHandler)ar.AsyncState;
dn.EndInvoke(ar);
}
public void Send(IPAddress Host, int port, byte[] Data)
{
try
{
IPEndPoint server = new IPEndPoint(Host, port);
int n = Data.Length;
if (UDP_Server != null)
{
UDP_Server.Send(Data, n, server);
}
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
//throw e;
}
}
private void CloseSocket()
{
if (UDP_Server != null)
UDP_Server.Close();
if (thdUdp != null)
{
Thread.Sleep(30);
thdUdp.Abort();
}
}
private void OpenSocket()//打开
{
Listener();
}
}