Extensions.cs 1.2 KB

123456789101112131415161718192021222324252627282930313233
  1. using System.Net.Sockets;
  2. namespace kcp2k
  3. {
  4. public static class Extensions
  5. {
  6. // 100k attempts of 1 KB increases = default + 100 MB max
  7. public static void SetReceiveBufferToOSLimit(this Socket socket, int stepSize = 1024, int attempts = 100_000)
  8. {
  9. // setting a too large size throws a socket exception.
  10. // so let's keep increasing until we encounter it.
  11. for (int i = 0; i < attempts; ++i)
  12. {
  13. // increase in 1 KB steps
  14. try { socket.ReceiveBufferSize += stepSize; }
  15. catch (SocketException) { break; }
  16. }
  17. }
  18. // 100k attempts of 1 KB increases = default + 100 MB max
  19. public static void SetSendBufferToOSLimit(this Socket socket, int stepSize = 1024, int attempts = 100_000)
  20. {
  21. // setting a too large size throws a socket exception.
  22. // so let's keep increasing until we encounter it.
  23. for (int i = 0; i < attempts; ++i)
  24. {
  25. // increase in 1 KB steps
  26. try { socket.SendBufferSize += stepSize; }
  27. catch (SocketException) { break; }
  28. }
  29. }
  30. }
  31. }