SocketUtils.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Net;
  4. using System.Net.Sockets;
  5. using System.Text;
  6. namespace Utilities
  7. {
  8. public class SocketUtils
  9. {
  10. public static void SetKeepAlive(Socket socket, TimeSpan timeout)
  11. {
  12. // The default settings when a TCP socket is initialized sets the keep-alive timeout to 2 hours and the keep-alive interval to 1 second.
  13. SetKeepAlive(socket, true, timeout, TimeSpan.FromSeconds(1));
  14. }
  15. /// <param name="timeout">the timeout, in milliseconds, with no activity until the first keep-alive packet is sent</param>
  16. /// <param name="interval">the interval, in milliseconds, between when successive keep-alive packets are sent if no acknowledgement is received</param>
  17. public static void SetKeepAlive(Socket socket, bool enable, TimeSpan timeout, TimeSpan interval)
  18. {
  19. socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
  20. // https://msdn.microsoft.com/en-us/library/dd877220.aspx
  21. byte[] tcp_keepalive = new byte[12];
  22. LittleEndianWriter.WriteUInt32(tcp_keepalive, 0, Convert.ToUInt32(enable));
  23. LittleEndianWriter.WriteUInt32(tcp_keepalive, 4, (uint)timeout.TotalMilliseconds);
  24. LittleEndianWriter.WriteUInt32(tcp_keepalive, 8, (uint)interval.TotalMilliseconds);
  25. socket.IOControl(IOControlCode.KeepAliveValues, tcp_keepalive, null);
  26. }
  27. /// <summary>
  28. /// Socket will be forcefully closed, all pending data will be ignored, and socket will be deallocated.
  29. /// </summary>
  30. public static void ReleaseSocket(Socket socket)
  31. {
  32. if (socket != null)
  33. {
  34. if (socket.Connected)
  35. {
  36. socket.Shutdown(SocketShutdown.Both);
  37. try
  38. {
  39. socket.Disconnect(false);
  40. }
  41. catch (SocketException)
  42. { }
  43. }
  44. socket.Close();
  45. socket = null;
  46. GC.Collect();
  47. GC.WaitForPendingFinalizers();
  48. }
  49. }
  50. }
  51. }