我使用的是:Android Studio/Java 1.8(客户端)VS2010/.NET 4.0(服务器)
此Java代码不断发送无效数据:
long FileSize = 1131666;
byte [] fs = ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN).putLong(FileSize).array();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write("FILE".getBytes());
baos.write(fs); //HERE
baos.write(GetHash().getHexStdstring().getBytes());
baos.write(dest_filename.getBytes());
OutputStream out = socket.getOutputStream();
out.write(baos.toByteArray());
out.flush();
这就是我得到的(用wireshark查看):
46:49:4c:45: ("FILE")
3f:44:11:00:00:00:00:00: (1131583)
32:37:64:35:36:61:32:34:32:36:31:30:37:36:37:32:30:65:34:38:66:37:34:65:36:61:64:38:34:65:36:30:65:64:33:63:66:64:34:36:32:64:36:62:37:65:62:64:62:32:63:63:62:37:37:64:36:38:37:66:64:64:66:39:
5c:45:75:72:6f:70:65:2e:70:6e:67
因此,我的C++服务器应用程序接收的值为1131583
,但无论我使用什么值作为FileSize
,我似乎总是在某个地方得到3f
。。。
另一个例子是当FileSize为22451663
时,我得到3f:3f:56:01:00:00:00:00
(或22429503
)。
有什么想法吗?
奇怪的是,如果我将fs
翻译回一个数字或字符串,并在发送之前Toast该值,它就会说它是正确的。
6:49:4c:45: ("FILE")
00:00:00:00:00:11:44:3f: (1131583)
无法复制,并且00:00:00:00:00:11:44:3f:
不是1131583的小端表示。它是1131583的big-endian表示。作为一个小的endian数,它是一个相当大的数:4347598471168。
打印的该代码在电线上实际产生的内容
ByteArrayOutputStream baos = new ByteArrayOutputStream()
{
public void write(byte[] bytes) throws IOException
{
for (byte b : bytes)
{
System.out.print(Integer.toHexString(b & 0xff)+":");
}
System.out.println();
super.write(bytes);
}
};
是:
46:49:4c:45:
92:44:11:0:0:0:0:0:
// etc.
此代码没有问题。
因此,0x3f
的ISO-8859-1字符是?
,而且似乎因为我将构建的ByteArayOutputStream发送到Send(String string)
函数,所以它将大量字节更改为0x3f
,就像0x92
没有ISO-8859-1字符一样。
我把我的代码改成这样:
// in main code
Bytestring message = new Bytestring(baos.toByteArray());
Send(message);
// send function
public void Send(Bytestring string) {
OutputStream out = socket.getOutputStream();
// other code for writing header
out.write(string.getBytes());
out.flush();
}
Bytestring是我基于字节数组创建的字符串类,而不是基于(2字节)char数组的string。