實作Java底層技術之IO模型與Selector
在Java程式設計中,IO(Input-Output)模型以及Selector是非常重要的底層技術,它們對於有效率地處理網路通訊和文件操作至關重要。在本文中,我們將深入探討Java中IO模型與Selector的實作原理,並提供具體的程式碼範例來幫助讀者更好地理解這些概念。
一、IO模型
二、Selector的使用
Selector是Java NIO函式庫中的重要元件,透過Selector可以實作單執行緒管理多個Channel的IO操作。 Selector提供了一個高效率的IO多工機制,可以大幅提高網路通訊的效率。
Selector的基本使用步驟如下:
public class Server { public static void main(String[] args) throws IOException { ServerSocketChannel serverSocket = ServerSocketChannel.open(); serverSocket.socket().bind(new InetSocketAddress(8888)); serverSocket.configureBlocking(false); Selector selector = Selector.open(); serverSocket.register(selector, SelectionKey.OP_ACCEPT); while (true) { int readyChannels = selector.select(); if (readyChannels == 0) continue; Set<SelectionKey> selectedKeys = selector.selectedKeys(); Iterator<SelectionKey> keyIterator = selectedKeys.iterator(); while (keyIterator.hasNext()) { SelectionKey key = keyIterator.next(); if (key.isAcceptable()) { SocketChannel client = serverSocket.accept(); client.configureBlocking(false); client.register(selector, SelectionKey.OP_READ); System.out.println("客户端连接:" + client.getRemoteAddress()); } else if (key.isReadable()) { SocketChannel client = (SocketChannel) key.channel(); ByteBuffer buffer = ByteBuffer.allocate(1024); int bytesRead = client.read(buffer); while (bytesRead > 0) { buffer.flip(); while (buffer.hasRemaining()) { System.out.print((char) buffer.get()); } System.out.println(); bytesRead = client.read(buffer); } } keyIterator.remove(); } } } }
public class Client { public static void main(String[] args) throws IOException { SocketChannel socket = SocketChannel.open(); socket.configureBlocking(false); socket.connect(new InetSocketAddress("localhost", 8888)); Selector selector = Selector.open(); socket.register(selector, SelectionKey.OP_CONNECT); while (true) { int readyChannels = selector.select(); if (readyChannels == 0) continue; Set<SelectionKey> selectedKeys = selector.selectedKeys(); Iterator<SelectionKey> keyIterator = selectedKeys.iterator(); while (keyIterator.hasNext()) { SelectionKey key = keyIterator.next(); if (key.isConnectable()) { if (socket.finishConnect()) { socket.register(selector, SelectionKey.OP_WRITE); System.out.println("客户端连接成功"); } } else if (key.isWritable()) { ByteBuffer buffer = ByteBuffer.allocate(1024); buffer.put("Hello, Server".getBytes()); buffer.flip(); while (buffer.hasRemaining()) { socket.write(buffer); } System.out.println("发送数据到服务端"); } keyIterator.remove(); } } } }
以上是如何實作Java底層技術之IO模型與Selector的詳細內容。更多資訊請關注PHP中文網其他相關文章!