【Java】AIO实例

一、blocking/non-blocking | sync/async

1.blocking/non-blocking: 描述的是方法会不会阻塞线程的执行,使线程进入blocking状态

2.sync/async:描述的是数据读写方式

  • sync:用户线程参与数据读写
  • 由内核线程发起读写,用户只需要关注I/O完成后的回调,不需要参与具体的I/O过程

二、AIO(Asynchronous Input and Output)

  1. NIO2.0提出了新异步通道概念,并提供了异步文件通道和异步套接字实现的通道(JDK7)
  2. 异步套接字通道真正的实现了真正的异步非阻塞I/O

三、三种IO工作原理

四、AIO模型

五、BIO、NIO、AIO

I/O数据传输时间实现方式使用场景应用
BIOStreamJDK1Socket连接数目比较小且固定的架构一般很少使用
NIOByteBufferJDK4Channel Selector连接数目多且连接比较短(轻操作)的架构网络框架netty
AIOByteBufferJDK7Channel连接数目多且连接比较长(重操作)的架构Ngix,MySQL新版本

六、AIO实现

//TestServer.java
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;

public class TestServer {
	
	private AsynchronousServerSocketChannel channel = null;
	
	public TestServer(int port) {
		
		try {
			channel = AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(port));
		} catch (IOException e) {
			e.printStackTrace();
		}

		channel.accept(null, new CompletionHandler<AsynchronousSocketChannel, Void>() {

			@Override
			public void completed(AsynchronousSocketChannel socket, Void attachment) {
				channel.accept(attachment, this);
				ByteBuffer byteBuffer = ByteBuffer.allocate(64);
				socket.read(byteBuffer);
				byteBuffer.flip();
				System.out.println(new String(byteBuffer.array()));
			}

			@Override
			public void failed(Throwable exc, Void attachment) {
				System.out.println("建立通信失败");
			}
		});
		
	}
	
	
	public static void main(String[] args) {
		new TestServer(9000);
		try {
			Thread.sleep(10000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}


}


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

public class TestClient {
	
	public static void main(String[] args) throws Exception {
		
		AsynchronousSocketChannel channel = AsynchronousSocketChannel.open();
		
		channel.connect(new InetSocketAddress("127.0.0.1", 9000));
		
		
		ByteBuffer buffer = ByteBuffer.allocate(64);
		
		buffer.put("hello".getBytes());
		
		buffer.flip();
		
		channel.write(buffer);
		
	}

}

  • 6
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值