的SocketChannel接收字节数组为空,则接收填充字节数组

问题描述 投票:-2回答:1

我想创建一个非阻塞套接字服务器和我通过一个套接字发送到服务器从客户端序列化对象。服务器接收一个空字节数组,但随后与序列化对象填充的字节数组。

final int value = channel.read(buffer);

if(value == -1){
    throw new IOException("End of stream");
}

final byte[] bytes = new byte[buffer.remaining()];

buffer.get(bytes, 0, bytes.length);

buffer.clear();

该代码我用于序列化的对象是

public static byte[] serialize(Object object) throws IOException {
    final ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
    final ObjectOutputStream stream = new ObjectOutputStream(byteStream);

    stream.writeObject(object);
    final byte[] bytes = byteStream.toByteArray();
    stream.close();
    byteStream.close();

    return bytes;
}

有两块来自这个码,一个字节数组,它是空的,并且其中填充了序列化对象的字节数组输出。首先,我接收到的空字节数组,再其次是填充的字节数组。

java nio bytebuffer socketchannel
1个回答
0
投票

由于user207421的评论,这个问题已经解决了。翻转缓冲液溶液。

© www.soinside.com 2019 - 2024. All rights reserved.