java nio示例
程序员文章站
2022-04-24 14:25:24
...
-
NIOServer.java
import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.Iterator; import java.util.Set; public class NIOServer { public static void main(String[] args) throws IOException { // Selector: multiplexor of SelectableChannel objects Selector selector = Selector.open(); // selector is open here // ServerSocketChannel: selectable channel for stream-oriented listening sockets ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); InetSocketAddress socketAddress = new InetSocketAddress("localhost", 1111); // Binds the channel's socket to a local address and configures the socket to listen for connections serverSocketChannel.bind(socketAddress); // Adjusts this channel's blocking mode. serverSocketChannel.configureBlocking(false); int ops = serverSocketChannel.validOps(); serverSocketChannel.register(selector, ops, null); // Infinite loop.. // Keep server running while (true) { log("i'm a server and i'm waiting for new connection and buffer select..."); // Selects a set of keys whose corresponding channels are ready for I/O operations selector.select(); // token representing the registration of a SelectableChannel with a Selector Set<SelectionKey> selectionKeys = selector.selectedKeys(); Iterator<SelectionKey> iterator = selectionKeys.iterator(); while (iterator.hasNext()) { SelectionKey currentKey = iterator.next(); // Tests whether this key's channel is ready to accept a new socket connection if (currentKey.isAcceptable()) { SocketChannel socketChannel = serverSocketChannel.accept(); // Adjusts this channel's blocking mode to false socketChannel.configureBlocking(false); // Operation-set bit for read operations socketChannel.register(selector, SelectionKey.OP_READ); log("Connection Accepted: " + socketChannel.getLocalAddress() + "\n"); // Tests whether this key's channel is ready for reading } else if (currentKey.isReadable()) { SocketChannel socketChannel = (SocketChannel) currentKey.channel(); ByteBuffer buffer = ByteBuffer.allocate(256); socketChannel.read(buffer); String result = new String(buffer.array()).trim(); log("Message received: " + result); if (result.equals("Crunchify")) { socketChannel.close(); log("\nIt's time to close connection as we got last company name 'Crunchify'"); log("\nServer will keep running. Try running client again to establish new connection"); } } iterator.remove(); } } } private static void log(String str) { System.out.println(str); } }
-
NIOClient
import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; import java.util.ArrayList; public class NIOClient { public static void main(String[] args) throws IOException, InterruptedException { InetSocketAddress socketAddress = new InetSocketAddress("localhost", 1111); SocketChannel socketChannel = SocketChannel.open(socketAddress); log("Connecting to Server on port 1111..."); ArrayList<String> companyDetails = new ArrayList<>(); // create a ArrayList with companyName list companyDetails.add("Facebook"); companyDetails.add("Twitter"); companyDetails.add("IBM"); companyDetails.add("Google"); companyDetails.add("Crunchify"); for (String companyName : companyDetails) { byte[] message = companyName.getBytes(); ByteBuffer buffer = ByteBuffer.wrap(message); socketChannel.write(buffer); log("sending: " + companyName); buffer.clear(); // wait for 2 seconds before sending next message Thread.sleep(2000); } socketChannel.close(); } private static void log(String str) { System.out.println(str); } }