java nio 例子
代码
public static void main(String[] args) throws Exception { // 创建通道和选择器 ServerSocketChannel socketChannel = ServerSocketChannel.open(); Selector selector = Selector.open(); InetSocketAddress inetSocketAddress = new InetSocketAddress( InetAddress.getLocalHost(), 4700); socketChannel.socket().bind(inetSocketAddress); // 设置通道非阻塞 绑定选择器 socketChannel.configureBlocking(false); socketChannel.register(selector, SelectionKey.OP_ACCEPT); System.out.println("Server started .... port:4700"); listener(selector); } public static void listener(Selector in_selector) { try { while (true) { in_selector.select(); // 阻塞 直到有就绪事件为止 Set<SelectionKey> readySelectionKey = in_selector .selectedKeys(); Iterator<SelectionKey> it = readySelectionKey.iterator(); while (it.hasNext()) { SelectionKey selectionKey = it.next(); // 判断是哪个事件 if (selectionKey.isAcceptable()) {// 客户请求连接 System.out.println(selectionKey.attachment() + " - 接受请求事件"); } if (selectionKey.isReadable()) {// 读数据 System.out.println(" - 读数据事件"); } if (selectionKey.isWritable()) {// 写数据 System.out.println(" - 写数据事件"); } if (selectionKey.isConnectable()) { System.out.println(" - 连接事件"); } // 必须removed 否则会继续存在,下一次循环还会进来, // 注意removed 的位置,针对一个.next() remove一次 it.remove(); } } } catch (Exception e) { e.printStackTrace(); } }