How can I set the buffer size for the underneath Socket UDP? C#

后端 未结 2 1602
清酒与你
清酒与你 2020-12-31 13:53

As we know for UDP receive, we use Socket.ReceiveFrom or UdpClient.receive

Socket.ReceiveFrom accept a byte array from you to put the udp data in.

UdpClient.

相关标签:
2条回答
  • 2020-12-31 14:30

    The issue with setting the ReceiveBufferSize is that you need to set it directly after creation of the UdpClient object. I had the same issue with my changes not being reflected when getting the value of ReceiveBufferSize.

    UdpClient client = new UdpClient()
    //no code inbetween these two lines accessing client.
    client.Client.ReceiveBufferSize = somevalue
    
    0 讨论(0)
  • 2020-12-31 14:49

    I use the .NET UDPClient often and I have always used the Socket.ReceiveBufferSize and have good results. Internally it calls Socket.SetSocketOption with the ReceiveBuffer parameter. Here is a some quick, simple, code you can test with:

    public static void Main(string[] args)
    {
      IPEndPoint remoteEp = null;
      UdpClient client = new UdpClient(4242);
      client.Client.ReceiveBufferSize = 4096;
    
      Console.Write("Start sending data...");
      client.Receive(ref remoteEp);
      Console.WriteLine("Good");
    
      Thread.Sleep(5000);
      Console.WriteLine("Stop sending data!");
      Thread.Sleep(1500);
    
      int count = 0;
      while (true)
      {
        client.Receive(ref remoteEp);
        Console.WriteLine(string.Format("Count: {0}", ++count));
      }
    }
    

    Try adjusting the value passed into the ReceiveBufferSize. I tested sending a constant stream of data for the 5 seconds, and got 10 packets. I then increased x4 and the next time got 38 packets.

    I would look to other places in your network where you may be dropping packets. Especially since you mention on your other post that you are sending 10KB packets. The 10KB will be fragmented when it is sent to packets the size of MTU. If any 1 packet in the series is dropped the entire packet will be dropped.

    0 讨论(0)
提交回复
热议问题