關於 Udp 收發 異步 和同步的對比


 

服務端代碼

class Program
    {
       static int count = 0;
       static DateTime dt = DateTime.Now;
        static void Main(string[] args)
        {
            UdpClient udp = new UdpClient(11220);

             StartRecv(udp);
            //while (true)
            //{
            //    IPEndPoint ipe = null;
            //    Console.WriteLine(Encoding.ASCII.GetString(udp.Receive(ref ipe)));
            //    if (count == 0)
            //        dt = DateTime.Now;
            //    count++;
            //    Console.WriteLine("recv count:" + count);
            //    Console.WriteLine("時間" + (DateTime.Now - dt).TotalMilliseconds);
            //}
            Console.Read();
        }
        static void StartRecv(UdpClient udp)
        {
            var v = udp.ReceiveAsync();
            v.ContinueWith((e) => {
                Console.WriteLine(Encoding.ASCII.GetString(e.Result.Buffer));
                if (count == 0)
                       dt = DateTime.Now;
                       count++;
                       Console.WriteLine("recv count:"+count);
                       Console.WriteLine("時間"+(DateTime.Now-dt).TotalMilliseconds);
                    StartRecv(udp); });
        }
    }

客戶端代碼

 class Program
    {
        static void Main(string[] args)
        {
            Random r = new Random();
            int count = 0;
            for (int x = 0; x < 10; x++)
            {
                Task.Run(() =>
                {
                    UdpClient udp = new UdpClient(r.Next(10000,50000));
                    for (int i = 0; i < 10000; i++)
                    {
                        byte[] b = Encoding.ASCII.GetBytes(i.ToString());
                        udp.SendAsync(b, b.Length, new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11220));
                        count++;
                        Console.WriteLine("發送計數"+count);
                    }
                });
            }
            Console.Read();
        }
    }

同步情況 

cpu占用情況

服務器結果 

 

 

異步:

cpu使用情況 

 

服務器結果 

 

 

 結論 在模擬客戶端 10個線程同時發送 1w個數據包 的情況下,明顯 異步占用cpu更多  發送的更快, 同步丟包少於異步,總的來說,異步比同步性能更好,發送更快,但是丟包也最多

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM