javaarraysserializationobjectoutputstream

Issue with serializing byte array in Java


I'm trying to send files from server to client via ObjectOutputStream. I thought it is an easier way to use this stream both for sending different objects as well as raw file data.

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. 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.

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:

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

Client 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. Note that the first MB of the file was sent correctly. If the file is less than one MB in size it is also being sent properly.


Solution

  • I guess problem was that stream saves each written 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);