给出“无法访问的代码”错误

时间:2014-09-23 01:45:55

标签: android sockets inputstream

美好的一天。有人可以帮助我。我似乎找不到解决这个问题的方法。我不知道为什么我会得到"无法访问的代码"我关闭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();
          }
  }

2 个答案:

答案 0 :(得分:0)

while (true) {}是一个无限循环,你并没有打破它,因此两个close()语句无法访问。

while循环内满足条件时,您可以使用break;语句继续执行while范围下的代码。

答案 1 :(得分: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)一直在循环播放。你需要打破时间才能进入下一行。在你的情况下它不会去下一行,因为没有结束。您可以将更改为,如果,它不是循环语句。