2010-02-10 76 views
2

我正在連接到Asp.Net中的TCP/IP端口,基本上我在這個端口上連接了一個設備,工作正常,但第二次當tcp偵聽器嘗試啓動時,它會產生上述錯誤。我怎樣才能擺脫 任何機構可以指導我這個錯誤的,這裏是我的代碼,我使用連接到TCP/IP端口:通常只允許使用每個套接字地址(協議/網絡地址/端口)

 try 
     {     
      byte[] ipaddress = new byte[4]; 
      string ip = ConfigurationManager.AppSettings["IP"].ToString(); 
      string[] ips = ip.Split('.'); 
      ipaddress[0] = (byte)Convert.ToInt32(ips[0]); 
      ipaddress[1] = (byte)Convert.ToInt32(ips[1]); 
      ipaddress[2] = (byte)Convert.ToInt32(ips[2]); 
      ipaddress[3] = (byte)Convert.ToInt32(ips[3]); 
      int portNumber = Convert.ToInt32(ConfigurationManager.AppSettings["Port"]); 
      tcpListener = new TcpListener(new IPAddress(ipaddress), portNumber); 
      tcpListener.Start(); 
      tcpClient = new TcpClient(); 
      tcpClient.NoDelay = true; 
      try 
      { 
       System.Threading.Thread.Sleep(60000); 
       tcpClient.ReceiveTimeout = 10; 
       tcpClient = tcpListener.AcceptTcpClient(); 
      } 
      catch (Exception ex) 
      { 
       tcpClient.Close(); 
       tcpListener.Stop(); 
      } 
      NetworkStream networkStream = tcpClient.GetStream(); 
      byte[] bytes = new byte[tcpClient.ReceiveBufferSize]; 
      try 
      { 
       networkStream.ReadTimeout = 2000; 
       networkStream.Read(bytes, 0, bytes.Length); 
      } 
      catch (Exception ex) 
      { 
       tcpClient.Close(); 
       tcpListener.Stop(); 
      } 
      string returndata = Encoding.Default.GetString(bytes); 
      tcpClient.Close(); 
      tcpListener.Stop(); 

      return returndata.Substring(returndata.IndexOf("0000000036"), 170); 
     } 
     catch (Exception ex) 
     { 
      if (tcpClient != null) 
       tcpClient.Close(); 
      tcpListener.Stop(); 
      LogError("Global.cs", "ReceiveData", ex); 
      ReceiveData(); 
     } 
當談到在這條線tcpListener.Start

();對於第二時間則生成錯誤 「只有每個套接字地址(協議/網絡地址/端口)中的一個的使用通常被許可」

+0

乍一看,我會建議聽者沒有正確關閉。 – Russell 2010-02-10 23:04:50

回答

0

你不使用關鍵字或最後塊利用的確保您的資源已關閉。

如果代碼中存在任何異常,則清理可能不會發生。你的多個catch塊可能得到所有場景,但是我不能通過閱讀代碼來輕易判斷。

的使用需要清理的資源通常優選的模式是:

using (MyResource res = new MyResource()) 
{ 
    // Do Stuff 
} 

如果MyResource實現IDisposable,或

try 
{ 
    MyResource res = new MyResource(); 
    // Do Stuff 
} catch (Exception ex) 
{ 
    // Whatever needs handing on exception 
} 
finally 
{ 
    res.Close(); // Or whatever call needs to be made to clean up your resource. 
} 
+0

我面臨同樣的問題,我已經檢查了所有使用連接的代碼塊,並且所有代碼塊都有結束連接的Finish塊。 這個異常阻止了我調試我的WebApplication。有誰知道如何擺脫這個問題? – MMalke 2012-09-21 14:27:50

+0

@MMalke:你有多個線程訪問連接嗎?此外,您可以將連接包裝在另一個實現了IDisposable的對象中,並記錄資源的打開和關閉,以便您可以看到打開但未關閉的位置。 – 2012-09-23 08:05:10

1

如果這是一個循環或東西,注意如果你的代碼沒有觸發任何異常,那麼連接就沒有關閉。只有在例外情況下才會關閉,這可能會在結尾處被捕獲catch

相關問題