我在尝试使用时遇到异常:
oos = new ObjectOutputStream(socketChannel.socket().getOutputStream());
oos.writeObject(o);
这引发了异常:
java.nio.channels.IllegalBlockingModeException
在非阻塞套接字中不能传递对象吗? 如果是,我应该如何继续通过套接字 channel 传递消息对象?
我已经在其他地方寻找过这个答案,但找不到...
最佳答案
您可能想要编写自己的 ObjectOutputStream
实现,它构造一个 ByteBuffer
并将其write()
发送到 channel 。
对于非阻塞套接字,你不能直接使用 channel 的套接字;您需要使用 channel 的 read()
和 write()
方法。
当您编写自己的 ObjectOutputStream
时,您主要需要覆盖 write()
方法来缓冲输出并使用 flush()
方法将缓冲区写入 channel 。然后,覆盖 writeObject()
方法,如下所示:
public void writeObject(Object o) throws IOException {
super.writeObject(o);
flush();
}
确保在每次写入对象后写入数据。
关于java - 通过 Java NIO 非阻塞套接字发送对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5638395/