Skip to content

Instantly share code, notes, and snippets.

@antopor
Last active August 29, 2015 14:16
Show Gist options
  • Save antopor/8ff3a0144ec86f24c380 to your computer and use it in GitHub Desktop.
Save antopor/8ff3a0144ec86f24c380 to your computer and use it in GitHub Desktop.
SetKeepAlive - activates keep-alive mechanism for TcpClient.
public static class TcpClientExtensions
{
/// <summary>
/// Activate Keep-Alive for TcpClient. Support only for Windows 2k and later
/// </summary>
/// <param name="client"></param>
/// <param name="keepAliveTime">Time (in milliseconds) with no activity on a socket</param>
/// <param name="keepAliveInterval">Interval (in milliseconds) between keep-alive packets. The number of packets depends on OS version.</param>
public static void SetKeepAlive(this TcpClient client, uint keepAliveTime, uint keepAliveInterval)
{
List<byte> bytes = new List<byte>();
bytes.AddRange(BitConverter.GetBytes((uint)(keepAliveTime != 0 ? 1 : 0)));
bytes.AddRange(BitConverter.GetBytes(keepAliveTime));
bytes.AddRange(BitConverter.GetBytes(keepAliveInterval));
client.Client.IOControl(IOControlCode.KeepAliveValues, bytes.ToArray(), null);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment