繁体   English   中英

在 Java 中序列化字节数组的问题

[英]Issue with serializing byte array in Java

我正在尝试通过 ObjectOutputStream 将文件从服务器发送到客户端。 我认为使用此 stream 发送不同的对象以及原始文件数据是一种更简单的方法。

我发送字节数组大小为Integer ,原始数据本身为byte[]和字节数组 hash 代码为Integer在循环中发送-1后完成服务器和客户端。 因此,每次迭代都会发送三个对象。

但是,它不能正常工作 - 客户端获得正确的大小和 hash,但在每次迭代中它也一次又一次地获得相同的byte[]数组。

客户端代码:

int size;
byte[] buf;
while ((size = (int) in.readObject()) > 0) {
    fOut.write((buf = (byte[]) in.readObject()), 0, size);
    System.out.printf("%d\tvs\t%d%n", Arrays.hashCode(buf), (int) in.readObject());
}

服务器代码:

byte[] buf = new byte[(int) MB];
int bufSize;
while ((bufSize = fileReader.read(buf)) != -1) {
    out.writeObject(bufSize);
    out.writeObject(buf);
    out.writeObject(Arrays.hashCode(buf));
}
out.writeObject(-1);

客户端和服务器的outin都是:

in = new ObjectInputStream(socket.getInputStream());
out = new ObjectOutputStream(socket.getOutputStream());

客户 output:

Connecting...
Connection established
-1060163348 vs  -1060163348
-1060163348 vs  1768685466
-1060163348 vs  861707881
-1060163348 vs  1055789475
-1060163348 vs  -79313434
-1060163348 vs  385231183
-1060163348 vs  -633252012
...

如您所见 - 所有字节 [] 都等于(

PS。 请注意,文件的第一个 MB 已正确发送。 如果文件大小小于 1 MB,则它也被正确发送。

我猜问题是 stream 保存了每个写入的 Object。 所以我从某种缓存中读取字节数组,而不是从套接字...

但是,它有帮助!

byte[] buf = new byte[(int) MB];
int bufSize;
while ((bufSize = fileReader.read(buf)) != -1) {
    out.writeObject(bufSize);
    out.writeObject(buf);
    out.writeObject(Arrays.hashCode(buf));
    out.reset(); // new line - it helps!!!!
}
out.writeObject(-1);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM