最近在写异步TCP程序,在调试时遇到了Client关闭后程序在接收回调里死循环,用client.Connected
检测好像也没用,在网上找到几篇用Socekt检测的文章,都还可以达到Client强行关闭后程序在退出死循环的功能。
本人这个是在原有的程序上加了一个小小的判断条件就实现了,相比起来也是比较简单的,其主要代码如下:
private void AcceptConnect()
{
IPAddress[] ip =
Dns.GetHostAddresses(Dns.GetHostName());
listener = new
TcpListener(ip[0], 60000);
listener.Start();
while
(isExit ==false)
{
try
{
allDone.Reset();
AsyncCallback callback = new
AsyncCallback(AcceptTcpClientCallback);
Console.Write("开始等待客户接入
\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("已经接受"
+ client.Client.RemoteEndPoint.ToString() + "连接");
SendString(readWriteObject, "服务器已经接受连接,请通话");
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("来自{0}:{1}\r\n",
readWriteObject.client.Client.RemoteEndPoint,
System.Text.Encoding.ASCII.GetString(readWriteObject.readBytes, 0,
Count)));
if (isExit == false && Count !=0) //添加的Count !=0 就可以退出死循环,
{
readWriteObject.InitReadArray();
readWriteObject.netStream.BeginRead(readWriteObject.readBytes, 0,
readWriteObject.readBytes.Length, ReadCallback, readWriteObject);
}
}
catch (Exception err)
{
Console.Write(err.ToString());
}
}