一、建立NioNest12類java
一個線程監聽5個端口的事件併發
public class NioTest12 { public static void main(String[] args) throws Exception { int[] ports = new int[5]; ports[0] = 5000; ports[1] = 5001; ports[2] = 5002; ports[3] = 5003; ports[4] = 5004; Selector selector = Selector.open(); for(int i = 0; i < ports.length; ++i){ ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.configureBlocking(false); ServerSocket serverSocket = serverSocketChannel.socket(); InetSocketAddress address = new InetSocketAddress(ports[i]); serverSocket.bind(address); serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); System.out.println("監聽端口:" + ports[i]); } while (true){ int numbers = selector.select(); System.out.println("numbers:" + numbers); Set<SelectionKey> selectionKeys = selector.selectedKeys(); System.out.println("selectedKeys: " + selectionKeys); Iterator<SelectionKey> iter = selectionKeys.iterator(); while (iter.hasNext()){ SelectionKey selectionKey = iter.next(); //判斷是否有客戶端鏈接 if(selectionKey.isAcceptable()){ ServerSocketChannel serverSocketChannel = (ServerSocketChannel)selectionKey.channel(); SocketChannel socketChannel = serverSocketChannel.accept(); socketChannel.configureBlocking(false); socketChannel.register(selector, SelectionKey.OP_READ); iter.remove(); System.out.println("得到客戶端鏈接:" +socketChannel); } //判斷是否有可讀的數據 else if(selectionKey.isReadable()){ SocketChannel socketChannel = (SocketChannel) selectionKey.channel(); int bytesRead = 0; while (true){ ByteBuffer byteBuffer = ByteBuffer.allocate(512); int read = socketChannel.read(byteBuffer); if(read <= 0){ break; } byteBuffer.flip(); socketChannel.write(byteBuffer); bytesRead += read; } System.out.println("讀取:" + bytesRead +", 來源於:" + socketChannel); iter.remove(); } } } } }
啓動NioTest12,監聽以下五個端口socket
使用命令行訪問命令行
二、telnet localhost 5000,併發送hello wold線程
輸出以下:3d
三、telnet localhost 5001,併發送hello woldserver
輸出以下:blog