.Net Socket keep-alive extension


/ Published in: C#
Save to your folder(s)

Sets the keep-alive interval for the socket.


Copy this code and paste it in your HTML
  1. namespace System.Net.Sockets
  2. {
  3. public static class SocketExtensions
  4. {
  5. private const int BytesPerLong = 4; // 32 / 8
  6. private const int BitsPerByte = 8;
  7.  
  8. /// <summary>
  9. /// Sets the keep-alive interval for the socket.
  10. /// </summary>
  11. /// <param name="socket">The socket.</param>
  12. /// <param name="time">Time between two keep alive "pings".</param>
  13. /// <param name="interval">Time between two keep alive "pings" when first one fails.</param>
  14. /// <returns>If the keep alive infos were succefully modified.</returns>
  15. public static bool SetKeepAlive(this Socket socket, ulong time, ulong interval)
  16. {
  17. try
  18. {
  19. // Array to hold input values.
  20. var input = new[]
  21. {
  22. (time == 0 || interval == 0) ? 0UL : 1UL, // on or off
  23. time,
  24. interval
  25. };
  26.  
  27. // Pack input into byte struct.
  28. byte[] inValue = new byte[3 * BytesPerLong];
  29. for (int i = 0; i < input.Length; i++)
  30. {
  31. inValue[i * BytesPerLong + 3] = (byte)(input[i] >> ((BytesPerLong - 1) * BitsPerByte) & 0xff);
  32. inValue[i * BytesPerLong + 2] = (byte)(input[i] >> ((BytesPerLong - 2) * BitsPerByte) & 0xff);
  33. inValue[i * BytesPerLong + 1] = (byte)(input[i] >> ((BytesPerLong - 3) * BitsPerByte) & 0xff);
  34. inValue[i * BytesPerLong + 0] = (byte)(input[i] >> ((BytesPerLong - 4) * BitsPerByte) & 0xff);
  35. }
  36.  
  37. // Create bytestruct for result (bytes pending on server socket).
  38. byte[] outValue = BitConverter.GetBytes(0);
  39.  
  40. // Write SIO_VALS to Socket IOControl.
  41. socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.KeepAlive, true);
  42. socket.IOControl(IOControlCode.KeepAliveValues, inValue, outValue);
  43. }
  44. catch (SocketException e)
  45. {
  46. Console.WriteLine("Failed to set keep-alive: {0} {1}", e.ErrorCode, e);
  47. return false;
  48. }
  49.  
  50. return true;
  51. }
  52. }
  53. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.