使用DataInputStream从TCP套接字读取字节之前的不需要的空字符

时间:2012-12-01 18:51:36

标签: java android tcp datainputstream nul

我正在编写一个Android应用程序,涉及连接到TCP服务器(我也写过)并从中发送/接收文本。现在我的最终阅读中有一个错误(客户端)。

当我在Eclipse中使用调试器时,它显示我正在接收所有发送的字节,但是对于某些文本,如果我期望 n 字节,我会得到第一个 n - k ,一些 m NUL字节,然后是最后的 k - m 有意义的字节。如果我正确地解释了这个问题,Java会看到大量的0并且决定之后没有什么用处(调试器显示字节数组和它转换为的字符串,但是如果我尝试的话会抛出它进一步检查)。

我怎样才能忽略NUL的大量涌入并阅读重要内容?

// Find out how many bytes we're expecting back
int count = dis.readInt(); // dis is a DataInputStream
dos.writeInt(count); // dos is a DataOutputStream

// Read that many bytes
byte[] received = new byte[count];
int bytesReceived = 0;
int bytesThisTime = 0;
while (-1 < bytesReceived && bytesReceived < count) {

    bytesThisTime = dis.read(received, 0, count);
    if (bytesThisTime <= 0) break;

    bytesReceived += bytesThisTime;
    String bytesToString = new String(received, 0, bytesThisTime, "UTF-8");
    sb_in.append(bytesToString);
    received = new byte[count];

}
in = sb_in.toString();

以下是正在编写的服务器代码:

            // Convert the xml into a byte array according to UTF-8 encoding
            // We want to know how many bytes we're writing to the client
            byte[] xmlBytes = xml.getBytes("UTF-8");
            int length = xmlBytes.length;

            // Tell the client how many bytes we're going to send
            // The client will respond by sending that same number back
            dos.writeInt(length);
            if (dis.readInt() == length) {
              dos.write(xmlBytes, 0, length); // All systems go - write the XML
            }

            // We're done here
            server.close();

2 个答案:

答案 0 :(得分:0)

替换:

String bytesToString = new String(received, "UTF-8");

使用:

String bytesToString = new String(received, 0, bytesThisTime, "UTF-8");

基本上dis.read(received, 0, count)可以在0和count之间返回任意数量的字节。 bytesThisTime告诉您此次读取了多少个字节。但是后来你使用的是整个数组,而不仅仅是实际读取的部分。

BTW考虑使用InputStreamReader为你动态解码字符串(但count将有不同的semantinc)。此外,请仔细阅读IOUtils API

答案 1 :(得分:0)

  

Java正在看到大量的0并且决定在

之后没有什么用处可读

没有。 Java根本不会查看数据,更不用说做出类似的语义决策了。

  

我怎样才能忽略NUL的大量涌入并阅读重要内容?

没有“大量涌入的NUL”被忽视。 Java不这样做,TCP没有这样做,没有做到这一点。

您自己的代码中只存在编程错误。

我可以无休止地详细说明这些内容,但实际上你应该使用DataInoutStream.readFully()而不是试图用你自己的bug版本来复制它。

相关问题