繁体   English   中英

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

[英]Unwanted nul characters preceding bytes from TCP socket read using DataInputStream

我正在编写一个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();

更换:

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

与:

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

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

顺便说一句,请考虑使用InputStreamReader ,它将为您即时解码字符串(但count会有不同的语义)。 此外,请通过IOUtils API仔细阅读。

Java看到了大量的0,并决定在此之后没有任何有用的东西可以读取

不。Java根本不查看数据,更不用说做出这样的语义决策了。

我该如何忽略NUL的大量涌入,而只阅读重要内容?

没有“ NUL的大量涌入”可以忽略。 Java不会那样做,TCP不会那样做,什么也不做。

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

我可以无休止地详细介绍这些内容,但从本质上讲,您应该使用DataInoutStream.readFully()而不是尝试使用您自己的臭虫缠身的版本来复制它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM