简体   繁体   English

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

[英]Issue with serializing byte array in Java

I'm trying to send files from server to client via ObjectOutputStream.我正在尝试通过 ObjectOutputStream 将文件从服务器发送到客户端。 I thought it is an easier way to use this stream both for sending different objects as well as raw file data.我认为使用此 stream 发送不同的对象以及原始文件数据是一种更简单的方法。

I'm sending byte array size as Integer , raw data itself as byte[] and byte array hash code as Integer in a loop, and finishing both server and client after sending -1 as size.我发送字节数组大小为Integer ,原始数据本身为byte[]和字节数组 hash 代码为Integer在循环中发送-1后完成服务器和客户端。 So, each iteration there are three objects to send.因此,每次迭代都会发送三个对象。

However, it's not working properly - the client gets the correct size and hash, but it also get same byte[] array again and again in each iteration.但是,它不能正常工作 - 客户端获得正确的大小和 hash,但在每次迭代中它也一次又一次地获得相同的byte[]数组。

Code of the client:客户端代码:

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());
}

Code of the server:服务器代码:

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);

Both out and in in both client and server are:客户端和服务器的outin都是:

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

Client output:客户 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
...

As you can see - all byte[] are equals(如您所见 - 所有字节 [] 都等于(

PS. PS。 Note that the first MB of the file was sent correctly.请注意,文件的第一个 MB 已正确发送。 If the file is less than one MB in size it is also being sent properly.如果文件大小小于 1 MB,则它也被正确发送。

I guess problem was that stream saves each written Object.我猜问题是 stream 保存了每个写入的 Object。 So I read byte array from some kind of cache, not from socket...所以我从某种缓存中读取字节数组,而不是从套接字...

However, it helps!但是,它有帮助!

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