BIO:同步阻塞模型。线程处理I/O请求时会阻塞(accept、read、write阻塞)。实现模式为一个线程处理一个连接,可用线程池优化。适合连接数少,并发量低的场景。如简单的文件传输。基于Socket和ServerSocket
NIO:同步非阻塞模型。通过Selector轮询通道Channel,非阻塞读写数据(select阻塞,accept、read、write非阻塞)。实现模式为一个线程通过seletor管理多个连接,适合高并发I/O 密集型的场景。如Web 服务器、实时通信系统。基于SocketChannel和ServerSocketChannel
AIO:异步非阻塞模型。基于事件驱动,I/O 操作由操作系统完成,通过回调(如 CompletionHandler)或Future返回结果。适合连接数较多且连接时间长的场景,如大型分布式系统
import java.net.;import java.nio. ;import java.nio.channels.;import java.util. ;
public class NIOServer{
public static void main(String[]a)throws Exception{
Selector s=Selector.open();
ServerSocketChannel ss=ServerSocketChannel.open();
ss.bind(new InetSocketAddress(9999));ss.configureBlocking(false);
ss.register(s,SelectionKey.OP_ACCEPT);
while(true){
s.select();
for(Iteratorit=s.selectedKeys().iterator();it.hasNext()😉{
SelectionKey k=it.next();it.remove();
if(k.isAcceptable()){
SocketChannel c=ss.accept();c.configureBlocking(false);
c.register(s,SelectionKey.OP_READ);
}else if(k.isReadable()){
SocketChannel c=(SocketChannel)k.channel();
ByteBuffer b=ByteBuffer.allocate(1024);
if(c.read(b)==-1){c.close();continue;}
b.flip();c.write(b);
}
}
}
}
}