Java NIO データグラム チャネルを (ブロッキング モードで) 使用しています。オブジェクトを一方から他方に送信したい。これは私が送信者側で行うことです:
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 の位置にリセットされ、最後のバイトが存在する位置まで上昇するはずです。