[FIXED] Problems serializing objects and sending over network

I don’t really know what im doing wrong, just trying to send an object called ‘packet’ from server to client using TCP.
This is how its serialized and sent server side


 bos = new ByteArrayOutputStream();
 objectOut = new ObjectOutputStream(bos);
 objectOut.writeObject(packet);
 String objectBytes = bos.toString();
					
 ps.println(objectBytes); // ps is a printstream, ps = new PrintStream(skt.getOutputStream());

Here is the client side code


 String data = br.readLine();

 byte[] objectData = data.getBytes();
 // Deserialize from a byte array
 bis = new ByteArrayInputStream(objectData);
 in = new ObjectInputStream(bis);
 packet = (Packet) in.readObject();
 in.close();

This is sending strings, i tried doing it by just sending a the length of the byte array, then the byte array and reciving it like that client side but just couldnt get it working. Ive had several errors probably most commen is this ‘java.io.StreamCorruptedException: invalid stream header’, but i also get a ‘java.io.EOFException’ error. Am i go going about this completely the wrong way?

Accidently ‘converting’ your binary data to text will corrupt your data.


 bos = new ByteArrayOutputStream();
 objectOut = new ObjectOutputStream(bos);
 objectOut.writeObject(packet);
 // String objectBytes = bos.toString();
@@ objectOut.close();
@@ byte[] data = objectOut.toByteArray();

@@ dataOutputStream.writeInt(data.length);
@@ dataOutputStream.write(data);
@@ dataOutputStream.flush();


@@  int len = dataInputStream.readInt();
@@  byte[] objectData = new byte[len];
@@  dataInputStream.readFully(objectData);
 // byte[] objectData = data.getBytes();

 // Deserialize from a byte array
 bis = new ByteArrayInputStream(objectData);
 in = new ObjectInputStream(bis);
 packet = (Packet) in.readObject();
 in.close();

Augh thanks, seems to be working now. Just buggy but thats the rest of my code i think :slight_smile: