I am using a java NIO Datagram Channel(in blocking mode). I want to transmit an object from one side to the other. This is what I do on the Sender Side:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(pkt);
ByteBuffer buffer = ByteBuffer.wrap(baos.toByteArray());
while(buffer.hasRemaining())
channel.write(buffer);
Here pkt
is my object of the class ControlPacket
to be transmitted. On the Receiver side:
ByteBuffer buffer = ByteBuffer.allocate(8192);
channel.receive(buffer);
buffer.flip();
ByteArrayInputStream bias = new ByteArrayInputStream(buffer.array(),0,buffer.limit());
ObjectInputStream ois = new ObjectInputStream(bias);
pkt = (ControlPacket)ois.readObject();
However I get java.io.StreamCorruptedException: invalid stream header: 00000094
error on running the code. Cannot figure out what is wrong in the code. I mean, since I flip the buffer after receiving it the pointer that reads it will be reset to 0 position and should go up till the position at which the last byte is there.
Close the ObjectOutputStream before writing the buffer.