Created
March 6, 2022 17:10
-
-
Save aidangannon/cb4e980ffccf56e5fad694c85d055ab2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 ) ); | |
} | |
} ); | |
} ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
using TCP keepalive