读我正在写涉及连接到TCP服务器(即我也写)和发送/从其接收文本Android应用。现在我在最后的阅读中有一个错误(客户端)。前述从TCP套接字字节不需要的NULL字符使用DataInputStream所
当我使用Eclipse中的调试器,它表明,我收到所有被发送的字节数,但对于文本的某些部分,如果我期待ñ字节,我会得到第一ñ - K,一些米 NUL字节,然后最终的k - 米有意义字节。如果我正确地解释了这个问题,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();
为了帮助调试,您可能要么添加记录到接收器,让你知道正是豆腐块它每次都得到了通过循环和它的所作所为与他们和/或使用数据包监控软件(tcpdump的/ WinDump的)来记录实际的数据包之间发送。手动测试两端对称于netcat的开放源代码程序也是非常有用的。 –