我正在编写一个涉及连接到 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();