Skip to content

Instantly share code, notes, and snippets.

@aidangannon
Created March 6, 2022 17:10
Show Gist options
  • Save aidangannon/cb4e980ffccf56e5fad694c85d055ab2 to your computer and use it in GitHub Desktop.
Save aidangannon/cb4e980ffccf56e5fad694c85d055ab2 to your computer and use it in GitHub Desktop.
var endpoint = new IPEndPoint( IPAddress.Loopback, 6000 );
var server = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
server.SetSocketOption( SocketOptionLevel.Tcp, SocketOptionName.KeepAlive, true );
server.SetSocketOption( SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, 90 );
server.SetSocketOption( SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval, 5 );
server.SetSocketOption( SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveRetryCount, 3 );
server.Bind( endpoint );
server.Listen( 1 );
Task.Run( ( ) =>
{
var client = server.Accept( );
Task.Run( ( ) =>
{
while( true )
{
client.Send( Encoding.UTF8.GetBytes( "hell from server to client" ) );
Thread.Sleep( 1000 );
}
} );
Task.Run( ( ) =>
{
while( true )
{
var bytes = new byte[ 20 ];
client.Receive( bytes );
Console.WriteLine( Encoding.UTF8.GetString( bytes ) );
}
} );
} );
var clientSocket = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
Task.Run( ( ) =>
{
clientSocket.Connect( endpoint );
Task.Run( ( ) =>
{
while( true )
{
clientSocket.Send( Encoding.UTF8.GetBytes( "hell from client to server" ) );
Thread.Sleep( 2000 );
}
} );
Task.Run( ( ) =>
{
while( true )
{
var bytes = new byte[ 20 ];
clientSocket.Receive( bytes );
Console.WriteLine( Encoding.UTF8.GetString( bytes ) );
}
} );
} );
@aidangannon
Copy link
Author

using TCP keepalive

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment