异步发包:
public void SendData(string ip,int port,object data) { IPEndPoint ipep = new IPEndPoint(IPAdress.Parse(ip), port); UdpClient udpClient=new UdpClient(); udpClient.BeginSend(data,data.Length,ipep,SendComplete,new AsyncCallbackArg(ip,udpClient)); }
///<summary>
///发送完成后的回调函数
///</summary>
///<param name="param"></param> private void sendComplete(IAsyncResult param) { AsyncCallbackArg arg=param.AsyncState as AsyncCallbackArg;//param.AsyncState 对应的就是BeginSend的最后一个参数state using(UdpClient client=(UdpClient)param.AsyncState) {
try
{ client.EndSend(param);//这句话必须得写,BeginSend()和EndSend()是成对出现的
}
catch(Exception ex)
{
....
}
}
//自己定义的返回状态参数类型 private struct AsyncCallbackArg { private UdpClient udpClient; private string ipAddress; public AsyncCallbackArg(string ip,string client) { udpClient=client; ipAddress=ip; } }
为防止丢包,收包时一个线程接收数据放到队列,而多个线程处理队列
或异步接收,代码如下:
private int m_Port;
private bool m_IsReceive;
private UdpClient m_ReceiveUdpClient;
private Thread m_ReceiveThread;
public void StartReceiveData(int port) {
m_IsReceive=true; m_Port=port; m_ReceiveThread=new Thread(); m_ReceiveThread.IsBackground=true; m_ReceiveThreads.start(); } private void Receive() { m_ReceiveUdpClient=new UdpClient(m_Port); byte[] data; while(m_IsReceive) { if(m_ReceiveUdpClient.Client==null) { break; } if(m_ReceiveUdpClient.Client.Poll(-1,SelectMode.Selectread)) { break; } try{ m_ReceiveUdpClient.BeginReceive(new AsyncCallBack(ReceiveComplete),m_ReceiveUdpClient); }catch(Exception ex){ .....} } } private void ReceiveComplete(IAsyncResult param) { UDPClient client=param.AsyncState as UDPClient ;//对应的就是BeginSend的最后一个参数state try { IPEndPoint ipep = new IPEndPoint(IPAdress.Any,m_Port); byte[] datas=client.EndReceive(param,ref ipep);//接受到的数据 } catch(Exception ex) { .... } }