using System; using System.Net.Sockets; using System.Runtime.InteropServices; namespace xServer.Core.Extensions { /// /// Socket Extension for KeepAlive /// /// Abdullah Saleem /// a.saleem2993@gmail.com public static class SocketExtensions { /// /// A structure used by SetKeepAliveEx Method /// [StructLayout(LayoutKind.Sequential)] internal struct TcpKeepAlive { internal uint onoff; internal uint keepalivetime; internal uint keepaliveinterval; }; /// /// Sets the Keep-Alive values for the current tcp connection /// /// Current socket instance /// Specifies how often TCP repeats keep-alive transmissions when no response is received. TCP sends keep-alive transmissions to verify that idle connections are still active. This prevents TCP from inadvertently disconnecting active lines. /// Specifies how often TCP sends keep-alive transmissions. TCP sends keep-alive transmissions to verify that an idle connection is still active. This entry is used when the remote system is responding to TCP. Otherwise, the interval between transmissions is determined by the value of the keepAliveInterval entry. public static void SetKeepAliveEx(this Socket socket, uint keepAliveInterval, uint keepAliveTime) { var keepAlive = new TcpKeepAlive { onoff = 1, keepaliveinterval = keepAliveInterval, keepalivetime = keepAliveTime }; int size = Marshal.SizeOf(keepAlive); IntPtr keepAlivePtr = Marshal.AllocHGlobal(size); Marshal.StructureToPtr(keepAlive, keepAlivePtr, true); var buffer = new byte[size]; Marshal.Copy(keepAlivePtr, buffer, 0, size); Marshal.FreeHGlobal(keepAlivePtr); socket.IOControl(IOControlCode.KeepAliveValues, buffer, null); } } }