最近在寫非同步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());
}
}