Java网络编程----AIO编程

一.介绍

      AIO编程,在NIO基础之上引入了异步通道的概念,并提供了异步文件和异步套接字通道的实现,从而在真正意义上实现了异步非阻塞.NIO只是非阻塞而并非异步.而AIO它不需要通过多路复用器对注册的通道进行轮询操作即可实现异步读写,从而简化了NIO编程模型.也可以称之为NIO2.0.这种模式才是真正属于我们的异步非阻塞的模型

     AsynchronousServerSocketChannel

     AsynchronousSocketChannel


二.代码示例

package com.east.aio;

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 Server {
	//线程池
	private ExecutorService executorService;
	//线程组
	private AsynchronousChannelGroup threadGroup;
	//服务器通道
	public AsynchronousServerSocketChannel assc;
	
	public Server(int port) {
		try {
			//创建一个缓冲池
			executorService = Executors.newCachedThreadPool();
			//创建线程组
			threadGroup = AsynchronousChannelGroup.withCachedThreadPool(executorService, 1);
			//创建服务器通道
			assc = AsynchronousServerSocketChannel.open(threadGroup);                 //异步非阻塞
			//进行绑定
			assc.bind(new InetSocketAddress(port));
			
			System.out.println("Server Start , Port : " + port);
			//进行阻塞
			assc.accept(this, new ServerCompletionHandler());     //获取客户端传来的异步信息
			//一直阻塞,不让服务停止
			Thread.sleep(Integer.MAX_VALUE);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
        Server server = new Server(8788);
	}

}

package com.east.aio;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.ExecutionException;

public class ServerCompletionHandler implements CompletionHandler {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
 
	}

	@Override
	public void completed(AsynchronousSocketChannel asc, Server attachment) {
		// TODO Auto-generated method stub
		//当有下一个客户端接入的时候,直接调用server的accept()方法,这样反复执行下去,保证多个客户端都能阻塞
		attachment.assc.accept(attachment,this);
		read(asc);
	}

	@Override
	public void failed(Throwable exc, Server attachment) {
		// TODO Auto-generated method stub
		exc.printStackTrace();
	}

	public void read(final AsynchronousSocketChannel asc){
		//读取数据
		ByteBuffer buf = ByteBuffer.allocate(1024);
		asc.read(buf, buf, new CompletionHandler() {

			@Override
			public void completed(Integer result, ByteBuffer attachment) {
				// TODO Auto-generated method stub
				//进行读取之后,重置标识位
				attachment.flip();
				//获得读取的字节数
				System.out.println("Server ->" + "收到客户端的数据长度为 :" + result);
				//获得读取的数据
				String resultData = new String(attachment.array()).trim();
				System.out.println("Server ->" + "收到客户端的数据信息为:" + resultData);
				String response = "服务器响应,收到了客户端发来的数据: "+ resultData;
				write(asc, response);
			}

			@Override
			public void failed(Throwable exc, ByteBuffer attachment) {
				// TODO Auto-generated method stub
				exc.printStackTrace();
			}
		});
	}
	
	private void write(AsynchronousSocketChannel asc,String response){
		try {
			ByteBuffer buf = ByteBuffer.allocate(1024);
			buf.put(response.getBytes());                //将数据写入ByteBuffer
			buf.flip();                                  //复位
			asc.write(buf).get();                        //开启一个新线程进行写操作
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

package com.east.aio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;

public class Client implements Runnable {

	private AsynchronousSocketChannel asc;
	
	public Client() throws Exception{
	  asc = AsynchronousSocketChannel.open();
	}
	
	public void connect(){
		asc.connect(new InetSocketAddress("127.0.0.1", 8788));
	}
	
	public void write(String request){
		try {
			asc.write(ByteBuffer.wrap(request.getBytes())).get();
			read();
		}catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void read(){
		ByteBuffer buf = ByteBuffer.allocate(1024);
		try {
			asc.read(buf).get();
			buf.flip();
			byte[] respByte = new byte[buf.remaining()];
			buf.get(respByte);
			System.out.println(new String(respByte,"utf-8").trim());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
       while(true){
    	   
       }
	}

	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
       Client c1 = new Client();
       c1.connect();
       
       Client c2 = new Client();
       c2.connect();
       
       Client c3 = new Client();
       c3.connect();
       
       new Thread(c1, "c1").start();
       new Thread(c2, "c2").start();
       new Thread(c3, "c3").start();
       
       Thread.sleep(1000);
       
       c1.write("c1 aaa");
       c2.write("c2 bbbb");
       c3.write("c3 ccccc");
	}

}


你可能感兴趣的:(Java,网络编程)