0

所以我的 android 应用程序中有这个非常奇怪的错误。我正在尝试连接到 TCP 服务器,并交换一些消息,其实并不复杂。我已经设法克服了它在开始时遇到的所有问题,但现在我被困在一个错误上,我希望有人知道如何修复它。

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

这是代码片段,向您展示这没什么大不了的。我在代码中没有更多内容,但是如果您需要查看其余部分,请询问。

提前致谢!

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);
        }
4

1 回答 1

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); 
   }
  }

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

于 2013-10-15T12:03:51.163 回答