zoukankan      html  css  js  c++  java
  • 关于 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更多  发送的更快, 同步丢包少于异步,总的来说,异步比同步性能更好,发送更快,但是丢包也最多

  • 相关阅读:
    springboot定时任务框架Quartz
    Linux中安装Erlang
    prometheus常用函数详解
    Prometheus+Grafana+SpringBoot业务埋点可视化监控
    Prometheus+Grafana可视化监控SpringBoot项目
    prometheus的数据类型介绍
    DS:顺序栈
    DS:顺序队列
    Linux:06进程
    primer5:chap09顺序容器
  • 原文地址:https://www.cnblogs.com/xiongyang123/p/11163627.html
Copyright © 2011-2022 走看看