0

I'm writing some networking code that writes basic packet constructs and sends them over a SocketChannel. I have the following relevant code:

in IOPacket (abstract implementation of the Packet interface, main thing getting sent over the channel):

//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;
}

in Connection (wrapper for a SocketChannel and all the behaviors needed to read, write, connect, etc.)

//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);
    ...
}

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.

Evan Hall
  • 58
  • 1
  • 8
  • You need to flip the byte buffer before you write it. – user207421 Aug 04 '16 at 23:43
  • @EJP I replaced the buf.position(0) at the end of IOPacket.write() with buf.flip(), but I still got the same exception. Did you mean something different by that? – Evan Hall Aug 05 '16 at 03:12

0 Answers0