Java 8
Java AIO的核心组件异步通道:包括服务端AsynchronousServerSocketChannel和普通AsynchronousSocketChannelCompletionHandler:用户处理器AsynchronousChannelGroup:用于资源共享的异步通道集合,将IO事件分配给CompletionHandler
构建网络服务端主程序:TigerServer.javapackage hxb.server;import java.io.IOException;import java.net.InetSocketAddress;import java.nio.channels.AsynchronousChannelGroup;import java.nio.channels.AsynchronousServerSocketChannel;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class TigerServer implements Runnable { // 服务器端口 private int port; // 异步通道组,共享资源池 private AsynchronousChannelGroup asyncChannelGroup; // 异步服务套接字通道 private AsynchronousServerSocketChannel serverSocketChannel; /** * 构造函数,完成服务端初始化 * * @param port * 监听端口 * @throws IOException */ public TigerServer(int port) throws IOException { this.port = port; ExecutorService executor = Executors.newFixedThreadPool(30); asyncChannelGroup = AsynchronousChannelGroup.withThreadPool(executor); serverSocketChannel = AsynchronousServerSocketChannel.open(asyncChannelGroup).bind(new InetSocketAddress(port)); } @Override public void run() { AcceptHandler acceptHandler = new AcceptHandler(); serverSocketChannel.accept(serverSocketChannel, acceptHandler); while(true) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) { try { new Thread(new TigerServer(9527)).start(); } catch (IOException e) { e.printStackTrace(); } }}
构建网路服务端Accept处理器:AcceptHandler.javapackage hxb.server;import java.io.IOException;import java.nio.ByteBuffer;import java.nio.channels.AsynchronousServerSocketChannel;import java.nio.channels.AsynchronousSocketChannel;import java.nio.channels.CompletionHandler;public class AcceptHandler implements CompletionHandler
构建网路服务端读数据处理器:ReadHandler.javapackage hxb.server;import java.io.IOException;import java.nio.ByteBuffer;import java.nio.channels.AsynchronousSocketChannel;import java.nio.channels.CompletionHandler;import java.nio.charset.CharacterCodingException;import java.nio.charset.Charset;import java.nio.charset.CharsetDecoder;public class ReadHandler implements CompletionHandler
构建客户端主程序:MonkeyClient.javapackage hxb.client;import java.io.IOException;import java.net.InetSocketAddress;import java.nio.channels.AsynchronousSocketChannel;public class MonkeyClient { public MonkeyClient() throws IOException { } public void start() { try { AsynchronousSocketChannel socketChannel = AsynchronousSocketChannel.open(); socketChannel.connect(new InetSocketAddress('127.0.0.1',9527),socketChannel,new ClientConnectHandler(1)); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { try { MonkeyClient client = new MonkeyClient(); client.start(); } catch (IOException e) { e.printStackTrace(); } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } }}