title: java.io.StreamCorruptedException: invalid stream header: 00000000 when reading from ObjectInputStream
body: <p>I'm writing some networking code that writes basic packet constructs and sends them over a SocketChannel. I have the following relevant code:</p>
  
  <p>in IOPacket (abstract implementation of the Packet interface, main thing getting sent over the channel):</p>
  
  <pre><code>//returns a bytebuffer representation of the object
  @Override
  public ByteBuffer write() throws IOException {
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      ObjectOutputStream oos = new ObjectOutputStream(baos);
      oos.writeObject(this);
      oos.flush();
      oos.close();
      ByteBuffer buf = ByteBuffer.wrap(baos.toByteArray());
      buf.position(0);
      return buf;
  }
  //returns a packet read from the given bytebuffer
  public static Packet read(ByteBuffer buffer) throws IOException {
      buffer.position(0);
      System.out.println("[SQNetEvents] Remaining: " + buffer.remaining());
      ByteArrayInputStream bais = new ByteArrayInputStream(buffer.array(), buffer.arrayOffset(), buffer.remaining());
      ObjectInputStream ois = new ObjectInputStream(bais);
      Packet packet = null;
      try {
          packet = (Packet) ois.readObject();
      }
      catch(Exception e) {
          throw new IOException("Read object is not an implementation of Packet");
      }
  
      ois.close();
      return packet;
  }
  </code></pre>
  
  <p>in Connection (wrapper for a SocketChannel and all the behaviors needed to read, write, connect, etc.)</p>
  
  <pre><code>//sends a packet to the associated address
  public void sendPacket(Packet packet) throws IOException {
      System.out.println("In sendPacket()");
      int length = getChannel().write(packet.write());
      System.out.println("[SQNetEvents] Sent packet of length " + length + " to " + getChannel().getRemoteAddress().toString());
  }
  private class ListenThread extends Thread {
      ...
      byte[] bytes = new byte[4096];
      ByteBuffer buffer = ByteBuffer.wrap(bytes);
      getChannel().read(buffer);
      System.out.println("In Connection$ListenThread.run()");
      Packet packet = IOPacket.read(buffer);
      ...
  }
  </code></pre>
  
  <p>I get the StreamCorruptedException on the IOPacket.read(ByteBuffer) call, from the ObjectInputStream constructor call. I've been able to successfully send a string literal ("String1") converted to a byte[] and then wrapped in a ByteBuffer over the SocketChannel and read it without dealing with the ByteArray or Object streams, so I know that the issue must be somewhere in the stream code. The code on both ends is identical, and blocking is configured true for the channels. Any help is appreciated, thanks.</p>