0
我正在使用java NIO数据报通道(处于阻塞模式)。我想从一侧传递一个对象到另一侧。这是我在发送端做:从ByteBuffer读取对象时StreamCorruptedException
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(pkt);
ByteBuffer buffer = ByteBuffer.wrap(baos.toByteArray());
while(buffer.hasRemaining())
channel.write(buffer);
这里pkt
是我的类ControlPacket
的对象进行传输。在接收方:
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();
但是,我得到java.io.StreamCorruptedException: invalid stream header: 00000094
运行代码时出错。无法弄清楚代码中的错误。我的意思是,由于我在接收到缓冲区后翻转了缓冲区,读取它的指针将被重置为0位置,并且应该上升到最后一个字节的位置。