0

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

当我在 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();
4

2 回答 2

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了多少字节。但后来您使用整个数组,而不仅仅是实际读取的部分。

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

于 2012-12-01T19:05:47.770 回答
0

Java is seeing the huge amount of 0s and deciding that there's nothing useful to be read after

No. Java doesn't look at the data at all, let alone make semantic decisions like that.

How can I ignore the massive influx of NUL and just read the important stuff?

There is no 'massive influx of NUL' to ignore. Java doesn't do that, TCP doesn't do that, nothing does that.

There are just programming errors in your own code.

I could detail those endlessly, but in essence you should be using DataInoutStream.readFully() instead of trying to replicate it with your own bug-ridden version.

于 2012-12-02T00:38:05.000 回答