AIOdemo源码 发表于 2018-02-21 server:12345678910111213141516171819202122232425262728293031323334353637383940414243package com.test.nio;import java.io.IOException;import java.net.InetSocketAddress;import java.nio.ByteBuffer;import java.nio.channels.AsynchronousServerSocketChannel;import java.nio.channels.AsynchronousSocketChannel;import java.nio.channels.CompletionHandler;import java.util.concurrent.ExecutionException;public class AIOServer { public AIOServer(int port) throws IOException{ final AsynchronousServerSocketChannel listener=AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(port)); listener.accept(null,new CompletionHandler<AsynchronousSocketChannel,Void>(){ @Override public void completed(AsynchronousSocketChannel ch, Void attachment) { listener.accept(null, this);//接受下一个链接 try { handler(ch); } catch (Exception e) { e.printStackTrace(); } } @Override public void failed(Throwable exc, Void attachment) { System.out.println("AIo失败!"); } }); } //真正逻辑处理 public void handler(AsynchronousSocketChannel ch) throws Exception, ExecutionException{ ByteBuffer bytebuffer=ByteBuffer.allocate(32); ch.read(bytebuffer).get(); bytebuffer.flip(); System.out.println("服务端接受数据"+new String(bytebuffer.array())); } public static void main(String[] args) throws Exception { AIOServer server =new AIOServer(7080); System.out.println("监听端口7080"); Thread.sleep(10000); }} client:123456789101112131415161718192021222324252627package com.test.nio;/** * Created by lifei on 16/11/9. */import java.net.InetSocketAddress;import java.nio.ByteBuffer;import java.nio.channels.AsynchronousSocketChannel;import java.util.concurrent.Future;public class AIOClient { private AsynchronousSocketChannel client=null; public AIOClient(String host,int port) throws Exception{ client =AsynchronousSocketChannel.open(); Future<?> future=client.connect(new InetSocketAddress(host,port)); System.out.println("返回结果:"+future.get()); } public void write(byte[] b){ ByteBuffer bytebuffer=ByteBuffer.allocate(32); bytebuffer.put(b); bytebuffer.flip(); client.write(bytebuffer); } public static void main(String[] args) throws Exception { AIOClient client=new AIOClient("localhost",7080); client.write("hello ...".getBytes()); }}