SocketUtils.cs 879 B

1234567891011121314151617181920212223242526
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Runtime.InteropServices;
  7. using System.Net.Sockets;
  8. namespace CSharpUtil.Extensions.Net
  9. {
  10. /// <summary>
  11. /// 辅助类
  12. /// </summary>
  13. public static class SocketUtils
  14. {
  15. public static void SetKeepAlive(this Socket sock, int interval_ms)
  16. {
  17. uint dummy = 0;
  18. byte[] inOptionValues = new byte[Marshal.SizeOf(dummy) * 3];
  19. BitConverter.GetBytes((uint)1).CopyTo(inOptionValues, 0);
  20. BitConverter.GetBytes((uint)interval_ms).CopyTo(inOptionValues, Marshal.SizeOf(dummy));
  21. BitConverter.GetBytes((uint)interval_ms).CopyTo(inOptionValues, Marshal.SizeOf(dummy) * 2);
  22. sock.IOControl(IOControlCode.KeepAliveValues, inOptionValues, null);
  23. }
  24. }
  25. }