Java AIO快速入门

作者:如沐春风 | 创建时间: 2023-03-30
Java AIO 是Java 7发布的新特性,支持异步方式处理消息,这里介绍Java AIO的核心组件以及简单样例...
Java AIO快速入门

操作方法

Java AIO的核心组件 异步通道:包括服务端AsynchronousServerSocketChannel和普通AsynchronousSocketChannel CompletionHandler:用户处理器 AsynchronousChannelGroup:用于资源共享的异步通道集合,将IO事件分配给CompletionHandler

构建网络服务端主程序:TigerServer.java package 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.java package 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<AsynchronousSocketChannel,AsynchronousServerSocketChannel> { @Override public void completed(AsynchronousSocketChannel result, AsynchronousServerSocketChannel attachment) { AsynchronousSocketChannel socketChannel = (AsynchronousSocketChannel)result; try { System.out.println("客戶端:"+socketChannel.getRemoteAddress()); socketChannel.write(ByteBuffer.wrap("Welcome to Tiger Server".getBytes())); //读取数据 startRead(socketChannel); } catch (IOException e) { e.printStackTrace(); } } private void startRead(AsynchronousSocketChannel socketChannel) { ByteBuffer buffer = ByteBuffer.allocate(1024); socketChannel.read(buffer, buffer, new ReadHandler(socketChannel)); } @Override public void failed(Throwable exc, AsynchronousServerSocketChannel attachment) { exc.printStackTrace(); } }

构建网路服务端读数据处理器:ReadHandler.java package 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<Integer,ByteBuffer>  { private AsynchronousSocketChannel socket; private CharsetDecoder decoder = Charset.forName("GBK").newDecoder(); public ReadHandler(AsynchronousSocketChannel socket) { this.socket = socket; } /** * result */ @Override public void completed(Integer result, ByteBuffer attachment) { Integer size = (Integer)result; ByteBuffer buffer = (ByteBuffer)attachment; if (size > 0) { buffer.flip(); try { System.out.println("收到" + socket.getRemoteAddress().toString() + "的消息:" + decoder.decode(buffer)); buffer.compact(); } catch (CharacterCodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } socket.read(buffer, buffer, this); } else if (size == -1) { try { System.out.println("客户端断线:" + socket.getRemoteAddress().toString()); buffer = null; } catch (IOException e) { e.printStackTrace(); } } } @Override public void failed(Throwable exc, ByteBuffer attachment) { exc.printStackTrace(); } }

构建客户端主程序:MonkeyClient.java package 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(); } } }

点击展开全文

更多推荐