为什么我的某些套接字数据被 "3f" 字节覆盖?

Why is some of my socket data getting overwritten with "3f" bytes?

本文关键字:3f 字节 覆盖 数据 我的 套接字 为什么      更新时间:2023-10-16

我使用的是: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。