多语言展示
当前在线:1265今日阅读:23今日分享:31

Java AIO快速入门

Java AIO 是Java 7发布的新特性,支持异步方式处理消息,这里介绍Java AIO的核心组件以及简单样例
工具/原料

Java 8

方法/步骤
1

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

2

构建网络服务端主程序: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(); } }}

3

构建网路服务端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 { @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(); }}

4

构建网路服务端读数据处理器: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  { 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(); }}

5

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

推荐信息