BufferedReader不从tcp服务器读取

时间:2013-10-15 11:37:46

标签: java android tcp bufferedreader

所以我在我的Android应用程序中有这个非常奇怪的错误。我正在尝试连接到TCP服务器,交换一些消息,真的没什么复杂的。我已经设法超越了它在开始时遇到的所有问题,但是现在我遇到了一个我希望有人知道如何修复的bug。

我连接到服务器并成功获取输入和输出流,但是当从服务器读取响应时,程序冻结。我研究了这个,我知道这是因为服务器没有消息。但我也知道服务器响应,因为我为iOS制作了相同的应用程序,它收到的一切都没问题。可以是一些Android问题吗?或者只是系统中的一些设置?

这是一段代码,告诉你这不是什么大问题。我在代码中没有更多东西,但是如果你需要查看剩下的内容,请询问。

提前致谢!

try {
            InetAddress serverAddr = InetAddress.getByName(serverIP);

            tcpSocket = new Socket(serverAddr, serverPort);
            Log.e("socket",
                    "created socket with " + serverIP
                            + Integer.toString(serverPort));

            out = new PrintWriter(new BufferedWriter(
                    new OutputStreamWriter(tcpSocket.getOutputStream())),
                    true);
            Log.e("socket", "output stream created alright");
            in = new BufferedReader(new InputStreamReader(
                    tcpSocket.getInputStream()));
            Log.e("socket", "input stream created alright");
            out.println("handheld#" + clientID + "#connection request");
            fromServer = in.read();
            while(fromServer != -1) {
                fromServer = in.read(); //updated, still no good
            }


            connected = true;
            Log.e("socket", "connect thread will finnish");
        } catch (UnknownHostException e) {
            Log.e("socket", "error finding host", e);
        } catch (IOException e) {
            Log.e("socket", "error creating socket's streams", e);
        }

1 个答案:

答案 0 :(得分:0)

希望以下代码正常工作

    InputStream in = tcpSocket.getInputStream();
    if(in == null)
     return null;
    Log.e("socket", "input stream created alright");
    out.println("handheld#" + "1111" + "#connection request");


    byte[] buff = new byte[1024];

    int read = -1;
    long totalRead = 0;
    while ((read = in.read(buff)) > 0) 
   {
    out.write(buff, 0, read);
    Log.i("readed Byte ", new String(buff));

    totalRead += read;
    if (totalRead % 100 * 1024 == 0) 
    { 
      System.out.printf("%d bytes read\n", totalRead); 
   }
  }

我在我的示例中实现了从输入流成功读取的内容。