C# 強制關閉socket後進入死迴圈問題)

來源:互聯網
上載者:User

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.