[英]Configurable blocking and non-blocking requests in NIO
I am planning to use java NIO for my project, but one of my requirement is to keep the requests configurable, ie the client can select the request to be: 1. blocking, 2. non blocking. 我打算将java NIO用于我的项目,但我的一个要求是保持请求可配置,即客户端可以选择以下请求:1。阻塞,2。非阻塞。
So, is it possible to use NIO in a sync. 那么,是否可以在同步中使用NIO。 way?
方式?
There is an option on the client code when creating the channel: 创建频道时,客户端代码上有一个选项:
SocketChannel socketChannel = SocketChannel.open();
socketChannel.configureBlocking(true);
But, I get this error when I make it as true. 但是,当我将其设为真时,我会收到此错误。
This is the client code I am using from this tutorial . 这是我在本教程中使用的客户端代码。
java.nio.channels.IllegalBlockingModeException
at java.nio.channels.spi.AbstractSelectableChannel.register(AbstractSelectableChannel.java:172)
at java.nio.channels.SelectableChannel.register(SelectableChannel.java:254)
at com.dds.client.DDSClient.run(DDSClient.java:77)
at java.lang.Thread.run(Thread.java:680)
The javadocs for register(...)
state that if you call the method on a channel that is in blocking mode, that exception will be thrown. register(...)
的javadoc声明如果在阻塞模式的通道上调用该方法, 则会抛出该异常。 A selector can only handle a non-blocking channel. 选择器只能处理非阻塞通道。
You need to change your code to use a blocking operations (eg read
or write
) rather than register
and select
when you want blocking semantics. 您需要更改代码以使用阻塞操作(例如
read
或write
),而不是在需要阻止语义时register
和select
。
You can't use select() on a blocking channel, as the Javadocs say. 正如Javadocs所说,你不能在阻塞通道上使用select()。 You more or less have to use the model of a thread per channel.
您或多或少必须使用每个通道的线程模型。
What is the reason for this strange requirement? 这个奇怪的要求是什么原因?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.