Skip to content

Instantly share code, notes, and snippets.

@EifelMono
Created July 8, 2014 07:20
Show Gist options
  • Save EifelMono/bb1735eedeb23ffdf968 to your computer and use it in GitHub Desktop.
Save EifelMono/bb1735eedeb23ffdf968 to your computer and use it in GitHub Desktop.
KeepAliveExtention
public static void UseKeepAlive(this TcpClient client, ulong time = 2000, ulong interval = 500)
{
if (client == null)
return;
// "consts" to help understand calculations
const int bytesperlong = 4; // 32 / 8
const int bitsperbyte = 8;
try
{
// resulting structure
byte[] SIO_KEEPALIVE_VALS = new byte[3 * bytesperlong];
// array to hold input values
ulong[] input = new ulong[3];
// put input arguments in input array
if (time == 0 | interval == 0) // enable disable keep-alive
input[0] = (0UL); // off
else
input[0] = (1UL); // on
input[1] = (time); // time millis
input[2] = (interval); // interval millis
// pack input into byte struct
for (int i = 0; i < input.Length; i++)
{
SIO_KEEPALIVE_VALS[i * bytesperlong + 3] = (byte)(input[i] >> ((bytesperlong - 1) * bitsperbyte) & 0xff);
SIO_KEEPALIVE_VALS[i * bytesperlong + 2] = (byte)(input[i] >> ((bytesperlong - 2) * bitsperbyte) & 0xff);
SIO_KEEPALIVE_VALS[i * bytesperlong + 1] = (byte)(input[i] >> ((bytesperlong - 3) * bitsperbyte) & 0xff);
SIO_KEEPALIVE_VALS[i * bytesperlong + 0] = (byte)(input[i] >> ((bytesperlong - 4) * bitsperbyte) & 0xff);
}
// create bytestruct for result (bytes pending on server socket)
byte[] result = BitConverter.GetBytes(0);
// write SIO_VALS to Socket IOControl
client.Client.IOControl(IOControlCode.KeepAliveValues, SIO_KEEPALIVE_VALS, result);
}
catch (Exception ex)
{
Log.HandleException(ex);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment