SocketUtil.cs 936 B

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