我正在开发一个Android应用程序,试图在一个套接字上从一个线程进行非阻塞写入,同时在另一个线程上进行阻塞读取。我正在查阅SocketChannel文档,试图弄清楚configureBlocking到底是做什么的。具体地说,如果我有一个非阻塞的SocketChannel,并且我用socketChannel.socket()访问附属的套接字,那么这个套接字在某种程度上也是非阻塞的吗?或者它被阻塞了?
换句话说,我能得到一个阻塞方向和一个非阻塞方向的效果吗?对于非阻塞方向使用非阻塞SocketChannel,而对另一个方向使用附属的Socket?
发布于 2012-07-05 22:56:33
如果Socket有一个关联的SocketChannel,则不能直接从它的InputStream中读取。你会得到IllegalBlockingModeException的。参见here。
你可以在非阻塞的SocketChannels上阻塞它们,方法是将它们registering到一个Selector并使用select()或select(long timeout)。这些方法通常会阻塞,直到注册通道就绪(或超时到期)。
对于不使用选择器的线程,通道仍然是非阻塞的。
here中修改过的示例
Selector selector = Selector.open();
channel.configureBlocking(false);
// register for OP_READ: you are interested in reading from the channel
channel.register(selector, SelectionKey.OP_READ);
while (true) {
int readyChannels = selector.select(); // This one blocks...
// Safety net if the selector awoke by other means
if (readyChannels == 0) continue;
Set<SelectionKey> selectedKeys = selector.selectedKeys();
Iterator<SelectionKey> keyIterator = selectedKeys.iterator();
while (keyIterator.hasNext()) {
SelectionKey key = keyIterator.next();
keyIterator.remove();
if (!key.isValid()) {
continue;
} else if (key.isAcceptable()) {
// a connection was accepted by a ServerSocketChannel.
} else if (key.isConnectable()) {
// a connection was established with a remote server.
} else if (key.isReadable()) {
// a channel is ready for reading
} else if (key.isWritable()) {
// a channel is ready for writing
}
}
}https://stackoverflow.com/questions/6769587
复制相似问题