2014-09-23 92 views
0

美好的一天。有人可以幫助我嗎?我似乎無法找到解決此問題的方法。我不知道爲什麼當我關閉InputStream和套接字時出現「無法訪問的代碼」錯誤。給「無法訪問的代碼」錯誤

感謝您的幫助。

public void run() { 
      try { 
      socket = new Socket(dstAddress, dstPort); 

      ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(1024); 
      byte[] buffer = new byte[1024]; 

      int bytesRead; 
      InputStream inputStream; 

      while (true) { 
       inputStream = socket.getInputStream(); 

       while ((bytesRead = inputStream.read(buffer)) != -1){ 
        byteArrayOutputStream.write(buffer, 0, bytesRead); 
        response += byteArrayOutputStream.toString("UTF-8"); 
       } 
       textResponse.setText(response); 
       if(response == "Server: You are connected to Android Server"){ 
        Log.v("ok","ppp"); 
       } 
       if(response == "OK"){ 
        Log.v("ok","ooo"); 
       } 
      } 

      inputStream.close(); --------unreachable code 
      socket.close();   --------unreachable code 

      } catch (UnknownHostException e) { 
      e.printStackTrace(); 
      response = "UnknownHostException: " + e.toString(); 
      } catch (IOException e) { 
      e.printStackTrace(); 
      response = "IOException: " + e.toString(); 
      } 
    } 
+0

控制不能從無限循環中出來,因此在某些情況下需要添加一些條件或循環。 – 2014-09-23 02:30:58

+1

'while(true)'是一個無限循環。 – 2014-09-23 04:45:05

回答

0

while (true) {}是一個永無止境的循環,你不能從中破壞,因此這兩個close()語句不可達。

當您的條件在while循環內符合時,您可以使用break;語句繼續執行while範圍以下的代碼。

0

t while(condition){ inputStream = socket.getInputStream();

   while ((bytesRead = inputStream.read(buffer)) != -1){ 
        byteArrayOutputStream.write(buffer, 0, bytesRead); 
        response += byteArrayOutputStream.toString("UTF-8"); 
       } 
       textResponse.setText(response); 
       if(response == "Server: You are connected to Android Server"){ 
        Log.v("ok","ppp"); 
       } 
       if(response == "OK"){ 
        Log.v("ok","ooo"); 
       } 
      } 

while (true)是循環所有的時間。你需要打破時間去下一行。在你的情況下,它不會去下一行,因爲沒有結束。您可能會更改如果,它它沒有循環語句。