UDP发包收包

异步发包:

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)  { ....  }
}

转载于:https://www.cnblogs.com/dashi/archive/2012/11/21/4034680.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值