java.io.StreamCorruptedException:从ObjectInputStream

时间:2016-08-04 21:00:49

标签: java networking io bytebuffer socketchannel

我正在编写一些编写基本数据包结构的网络代码,并通过SocketChannel发送它们。我有以下相关代码:

在IOPacket中的

(Packet接口的抽象实现,通过频道发送的主要内容):

//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;
}
Connection中的

(SocketChannel的包装器以及读,写,连接等所需的所有行为)

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

我从ObjectInputStream构造函数调用中获取IOPacket.read(ByteBuffer)调用的StreamCorruptedException。我已经能够成功发送一个字符串文字(" String1")转换为byte [],然后通过SocketChannel包装在ByteBuffer中并读取它而不处理ByteArray或Object流,所以我知道问题必须在流代码中的某个地方。两端的代码相同,并且阻塞配置为通道的true。感谢任何帮助。谢谢。

0 个答案:

没有答案