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

  • 相关阅读:
    装饰器结合cookie
    day12(输出重定向)
    day13(软件包管理)
    day11(acl权限/特殊属性/su与sudo)
    day10(权限)
    day09(用户管理)
    day08(打包压缩zip和tar)
    day07 文件管理(上传与下载/字符处理命令sort/uniq/cut与tr/wc)
    day06(find命令 name/size/type)
    day05(文件的修改vi和vim/移动文件mv/删除文件rm)
  • 原文地址:https://www.cnblogs.com/dashi/p/4034680.html
Copyright © 2020-2023  润新知