2011-07-20 80 views
1

我正在开发一个Android应用程序,试图从一个套接字上的一个线程进行非阻塞写入,同时在另一个线程上执行阻塞读取。我正在浏览SocketChannel文档,并试图找出configureBlocking的功能。具体来说,如果我有一个非阻塞的SocketChannel,并且我使用socketChannel.socket()访问附属的Socket,那么Socket在某种程度上也是非阻塞的吗?还是阻塞?使用非阻塞的SocketChannel,是否阻塞了Socket?

换句话说,我可以通过在非阻塞方向上使用非阻塞SocketChannel,并在其他方向上使用附属Socket来获得一个阻塞方向和一个非阻塞方向的效果吗?

回答

0

如果Socket有一个关联的SocketChannel,则不能直接读取它的InputStream。你会得到IllegalBlockingModeException。见here

您可以通过registering阻止非阻塞SocketChannel到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 
    } 
    } 
}