(C # TCP asynchronous) client abnormal disconnect, server monitoring use KeepAlive

In a recent project is done with C # as the server, the client every 10 seconds to initiate a connection, the question arises: Since the students do have some client-side bug yet resolved, the client would often collapse out, but the server was not detected abnormal disconnect socket.

After check the information found there are two ways to solve:

1, a heartbeat packet mode (every few seconds, the server sends a request to the client, if the client receives no response, it is determined that the client offline)

2, KeepAlive mechanism with the socket (personal feeling and heartbeat packet somewhat similar)

 

I first used the heartbeat packet mode test, we found that although indeed the corresponding socket is closed, but a large delay (after the establishment of the socket connection, the client off the network 5s-20s, the server will disconnect socket connection), so choose to use KeepAlive mechanism.

 

Server the Socket; 

// Server bound port and listening not posted out 

the Socket Client = server.accept (); 

client.IOControl (IOControlCode.KeepAliveValues, the KeepAlive ( . 1 , 3000 , 500 ), null ); // set Keep- Alive parameter 
  
Private  byte [] the KeepAlive ( int onoff, int keepAliveTime, int KeepAliveInterval) 
{ 
        uint dummy = 0 ;
         byte [] = inOptionValues new new  byte [Marshal.SizeOf (dummy) * . 3 ]; 
        BitConverter.GetBytes ((uint)onOff).CopyTo(inOptionValues, 0);
        BitConverter.GetBytes((uint)keepAliveTime).CopyTo(inOptionValues, Marshal.SizeOf(dummy));//keep-alive间隔(单位ms)
        BitConverter.GetBytes((uint)keepAliveInterval).CopyTo(inOptionValues, Marshal.SizeOf(dummy) * 2);// 尝试间隔(单位ms)
        return inOptionValues;
}

 

  

After setting up the further need for close method is performed in the client socket catch Receive asynchronous callback's (or EndReceive performed in the try next BeginReceive).

But it seems to use TcpClient not need to be performed manually close the Receive asynchronous callback function (test yet, make up after the next test).

 

 

 

 

Guess you like

Origin www.cnblogs.com/garfield-bc/p/11979044.html