When tcpclient is used for network connection, client connection is often interrupted due to an exception. The server must set a detection method to handle the exception.
For short connections, you can set an appropriate value for the socket attribute receivetimeout and sendtimeout. When reading/writing times out, a socketexception occurs. Check this exception and handle it. server connection ProcessingCodeExample:
While (newclient. Connected & isconnected)
{
NS. Readtimeout = 60000; // frist, 60 s
Newclient. Client. sendtimeout = 1000;
Int bytesread = 0;
Try
{
Bytesread = NS. Read (buffer, 0, buffer. Length); // reads data and replies Based on the Content
If (bytesread = 1)
{
// String receiveinfo = encoding. ASCII. getstring (buffer, 0, bytesread );
Protocol type cmd = (protocol type) buffer [0];
Connect. receiveinfo = cmd. tostring (); // Save the stored information
If (receivedata! = NULL)
{
Eventargs E = new eventargs ();
Receivedata (this, e );
}
NS.Readtimeout= 1000; // decrease to 1 s
// Response Request Response
String response = "hello ";
Buffer = encoding. utf8.getbytes (string. Format ("[{0: D4}] {1}", ID, response ));
NS. Write (buffer, 0, buffer. Length );
}
Thread. Sleep (100 );
}
Catch
{
Bytesread = 0;
Isconnected = false; // terminate the connection immediately if an exception occurs.
}
}
Newclient. Close ();
Persistent connections can be processed through the heartbeat detection mechanism in the socket.
The underlying I/O of socket is generally set through the wsaioctl function. C # encapsulates this function, that isSocket.Iocontrol method.
Public
Iocontrol(IocontrolcodeIocontrolcode,
[]Optioninvalue,
[]Optionoutvalue)
The first parameter is the socket Io control code, the second parameter is the input parameter value, and the third parameter is the output value.
InWinSock 2 defines manySocket Io control type, Which has one of the following items:Keepalivevalues controls the sending and sending interval of TCP keep-alive packets. The default value is 2 hours. When the interval exceeds this setting, the socket will send 5 connection signals consecutively. If the client does not respond, the client socket will be disconnected.
We can adjust the interval as follows:
Newclient. Client. iocontrol (iocontrolcode. keepalivevalues, bitconverter. getbytes (120), null); // set to 2 minutes.
the preceding two methods are used to detect abnormal network connection disconnections.