Recently, I was writing an asynchronous TCP program. When the client was closed during debugging, the program had an endless loop in the receive callback, using client. Connected
Detection seems useless. I have found several articles on the Internet that use socekt to detect. They can also enable the function that the program exits the endless loop after the client is forcibly disabled.
I added a small judgment condition to the original program, which is relatively simple. The main code is as follows:
Private void acceptconnect ()
{
IPaddress [] IP =
DNS. gethostaddresses (DNS. gethostname ());
Listener = new
Tcplistener (IP Address [0], 60000 );
Listener. Start ();
While
(Isexit = false)
{
Try
{
Alldone. Reset ();
Asynccallback callback = new
Asynccallback (accepttcpclientcallback );
Console. Write ("start waiting for customer access
\ N \ r ");
Listener. beginaccepttcpclient (callback,
Listener );
Alldone. waitone ();
}
Catch
(Exception ERR)
{
Console. Write (ERR. tostring ());
Break;
}
}
}
Private void accepttcpclientcallback (iasyncresult AR)
{
Tcplistener mylistener = (tcplistener) Ar. asyncstate;
Try
{
Alldone. Set ();
Tcpclient client =
Mylistener. endaccepttcpclient (AR );
Alarmtcpobject readwriteobject =
New alarmtcpobject (client );
Console. Out. Write ("accepted"
+ Client. Client. remoteendpoint. tostring () + "connection ");
Sendstring (readwriteobject, "the server has accepted the connection, please call ");
Readwriteobject. netstream. beginread (readwriteobject. readbytes, 0,
Readwriteobject. readbytes. length, readcallback, readwriteobject );
}
Catch (exception ERR)
{
Return;
}
}
Private void readcallback (iasyncresult AR)
{
Try
{
Alarmtcpobject readwriteobject =
(Alarmtcpobject) Ar. asyncstate;
Int COUNT =
Readwriteobject. netstream. endread (AR );
Byte [] tempforxmsg = new
Byte [count];
Console. Out. Write (string. Format ("from {0 }:{ 1} \ r \ n ",
Readwriteobject. Client. Client. remoteendpoint,
System. Text. encoding. ASCII. getstring (readwriteobject. readbytes, 0,
Count )));
If (isexit = false & count! = 0)// Added count! = 0 to exit the endless loop,
{
Readwriteobject. initreadarray ();
Readwriteobject. netstream. beginread (readwriteobject. readbytes, 0,
Readwriteobject. readbytes. length, readcallback, readwriteobject );
}
}
Catch (exception ERR)
{
Console. Write (ERR. tostring ());
}
}