NIO(NO-Blocking I/O)模型

时间:2024-07-13 12:48:46
import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.*; import java.util.Iterator; import java.util.Set; public class SimpleNioServer { public void startServer(int port) throws IOException { Selector selector = Selector.open(); ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.bind(new InetSocketAddress(port)); serverSocketChannel.configureBlocking(false); serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); while (true) { selector.select(); // Wait for an event Set<SelectionKey> selectedKeys = selector.selectedKeys(); Iterator<SelectionKey> iter = selectedKeys.iterator(); while (iter.hasNext()) { SelectionKey key = iter.next(); if (key.isAcceptable()) { registerClient(serverSocketChannel, selector); } if (key.isReadable()) { answerClient(key); } iter.remove(); } } } private void registerClient(ServerSocketChannel serverSocketChannel, Selector selector) throws IOException { SocketChannel clientChannel = serverSocketChannel.accept(); clientChannel.configureBlocking(false); clientChannel.register(selector, SelectionKey.OP_READ); System.out.println("New client connected: " + clientChannel); } private void answerClient(SelectionKey key) throws IOException { SocketChannel clientChannel = (SocketChannel) key.channel(); ByteBuffer buffer = ByteBuffer.allocate(256); int read = clientChannel.read(buffer); if (read == -1) { clientChannel.close(); System.out.println("Client disconnected: " + clientChannel); return; } buffer.flip(); while (buffer.hasRemaining()) { clientChannel.write(buffer); } buffer.clear(); } public static void main(String[] args) { SimpleNioServer server = new SimpleNioServer(); try { server.startServer(8080); } catch (IOException e) { e.printStackTrace(); } } }