|
| 1 | +package com.brianway.learning.java.nio.tutorial; |
| 2 | + |
| 3 | +import java.io.IOException; |
| 4 | +import java.net.InetSocketAddress; |
| 5 | +import java.nio.channels.SelectionKey; |
| 6 | +import java.nio.channels.Selector; |
| 7 | +import java.nio.channels.ServerSocketChannel; |
| 8 | +import java.util.Iterator; |
| 9 | +import java.util.Set; |
| 10 | + |
| 11 | +/** |
| 12 | + * Full Selector Example |
| 13 | + * 启动后,浏览器输入 localhost:9999 |
| 14 | + * |
| 15 | + * @auther brian |
| 16 | + * @since 2019/6/24 22:29 |
| 17 | + */ |
| 18 | +public class SelectorDemo { |
| 19 | + |
| 20 | + public static void main(String[] args) throws IOException { |
| 21 | + Selector selector = Selector.open(); |
| 22 | + ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); |
| 23 | + serverSocketChannel.socket().bind(new InetSocketAddress(9999)); |
| 24 | + serverSocketChannel.configureBlocking(false); |
| 25 | + |
| 26 | + // SelectionKey key = |
| 27 | + serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); |
| 28 | + |
| 29 | + while (true) { |
| 30 | + |
| 31 | + int readyChannels = selector.selectNow(); |
| 32 | + |
| 33 | + if (readyChannels == 0) { |
| 34 | + // System.out.println("readyChannels == 0"); |
| 35 | + continue; |
| 36 | + } |
| 37 | + |
| 38 | + Set<SelectionKey> selectedKeys = selector.selectedKeys(); |
| 39 | + |
| 40 | + Iterator<SelectionKey> keyIterator = selectedKeys.iterator(); |
| 41 | + |
| 42 | + while (keyIterator.hasNext()) { |
| 43 | + |
| 44 | + SelectionKey key = keyIterator.next(); |
| 45 | + |
| 46 | + if (key.isAcceptable()) { |
| 47 | + // a connection was accepted by a ServerSocketChannel. |
| 48 | + System.out.println("accepted"); |
| 49 | + } else if (key.isConnectable()) { |
| 50 | + // a connection was established with a remote server. |
| 51 | + System.out.println("connectable"); |
| 52 | + } else if (key.isReadable()) { |
| 53 | + // a channel is ready for reading |
| 54 | + System.out.println("ready"); |
| 55 | + } else if (key.isWritable()) { |
| 56 | + // a channel is ready for writing |
| 57 | + System.out.println("writable"); |
| 58 | + } |
| 59 | + |
| 60 | + keyIterator.remove(); |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | +} |
0 commit comments