JAVA aio简单使用

Posted 你还未发现

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JAVA aio简单使用相关的知识,希望对你有一定的参考价值。

使用aio,实现客户端和服务器 对一个数进行轮流累加

//服务器端
public class Server {
    private static ExecutorService executorService = Executors.newFixedThreadPool(4);
    public static void main(String[] args) {
        try {
            AsynchronousChannelGroup group=AsynchronousChannelGroup.withThreadPool(executorService);
            AsynchronousServerSocketChannel server=AsynchronousServerSocketChannel.open(group);
            server.bind(new InetSocketAddress(8881));
            server.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {

                @Override
                public void completed(AsynchronousSocketChannel client, Object attachment) {
                    server.accept(null, this);
                    try {
                        System.out.println("服务器收到客户端"+client.getRemoteAddress().toString());
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    ByteBuffer buffer=ByteBuffer.allocate(1024);
                    client.read(buffer, buffer, new CompletionHandler<Integer, ByteBuffer>() {

                        @Override
                        public void completed(Integer index, ByteBuffer buffer) {
                            try {
                            buffer.flip();
                            int i=buffer.getInt(0);
                            System.out.println(Thread.currentThread().getName()+" 服务器收到客户端消息"+client.getRemoteAddress().toString()+ "   "+i);
                            buffer.putInt(0, i+1);
                            client.write(buffer).get();//这个是异步的,一定要用get 确保执行结束 才能clear
                            buffer.clear(); 
                            client.read(buffer,buffer,this);
                            }catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void failed(Throwable exc, ByteBuffer attachment) {
                            throw new RuntimeException(exc.getMessage());
                            
                        }
                    });
                    
                }

                @Override
                public void failed(Throwable exc, Object attachment) {
                    throw new RuntimeException(exc.getMessage());
                    
                }
                
            });
            while(true) {
                Thread.sleep(2000);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
//客户端
public class Client {
    public static void main(String[] args) {
        try {
            AsynchronousSocketChannel client=AsynchronousSocketChannel.open();
            client.connect(new InetSocketAddress("127.0.0.1", 8881), null, new CompletionHandler<Void, Object>() {

                @Override
                public void completed(Void result, Object attachment) {
                    System.out.println("连接服务器成功");
                    ByteBuffer buffer=ByteBuffer.allocate(1024);
                    buffer.putInt(0,1);
                    try {
                        client.write(buffer).get();
                    } catch (InterruptedException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    } catch (ExecutionException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                    buffer.clear();
                    client.read(buffer, buffer, new CompletionHandler<Integer, ByteBuffer>() {

                        @Override
                        public void completed(Integer result, ByteBuffer buffer) {
                            try {
                                //System.out.println("result="+result+" postition="+buffer.position()+" limit="+buffer.limit());
                                buffer.flip();
                                int i=buffer.getInt(0);
                                System.out.println("客户端收到服务器返回的消息"+client.getRemoteAddress().toString()+" "+i);
                                buffer.putInt(0, i+1);
                                Thread.sleep(2000);
                                client.write(buffer).get();
                                buffer.clear();
                                client.read(buffer, buffer, this);
                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            } catch (InterruptedException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            } catch (ExecutionException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                            
                        }

                        @Override
                        public void failed(Throwable exc, ByteBuffer attachment) {
                            throw new RuntimeException(exc.getMessage());
                            
                        }
                    });
                    
                }

                @Override
                public void failed(Throwable exc, Object attachment) {
                    throw new RuntimeException(exc.getMessage());
                }
            });
            while(true) {
                Thread.sleep(2000);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

以上是关于JAVA aio简单使用的主要内容,如果未能解决你的问题,请参考以下文章

Java BIO与NIO以及AIO分析

Java IO 基础

也谈BIO | NIO | AIO (Java版--转)

初理解Java中的BIO,NIO,AIO

BIO NIO AIO

java 简单的代码片段,展示如何将javaagent附加到运行JVM进程