Java|Java NIO简单例子

【Java|Java NIO简单例子】例子如下:

Selector selector; try { selector = Selector.open(); SocketChannel socketChannel = SocketChannel .open(new InetSocketAddress("192.168.91.109", 4321)); socketChannel.configureBlocking(false); socketChannel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE); while (selector.select() > 0) { Set set = selector.selectedKeys(); for (SelectionKey sk : set) { SocketChannel sc = (SocketChannel) sk.channel(); if (sk.isReadable()) { Log.i("MainActivity", "channel is readable"); }if (sk.isWritable()) { Log.i("MainActivity", "channel is writable"); } } } } catch (IOException e) { e.printStackTrace(); }

对于客户端而言,socket链接通常只有一个,一般Selector的select方法循环用在读线程里面,当select方法返回时,就去read,然后处理。而写操作单独用在另外一个线程里面操作,并且是不需要进行select的,拿到数据就写入socket,因为write方法是阻塞的,write方法返回就说明socket是可以写的。

    推荐阅读