1. 程式人生 > >Netty之BIO(同步阻塞IO)、PIO(偽非同步阻塞IO)、NIO(非同步非阻塞IO)、AIO(非同步非阻塞IO)、Netty

Netty之BIO(同步阻塞IO)、PIO(偽非同步阻塞IO)、NIO(非同步非阻塞IO)、AIO(非同步非阻塞IO)、Netty

學習書籍:Netty權威指南

多種IO方式的比較:

1、BIO(同步阻塞IO)

使用ServerSocket繫結IP地址和監聽埠,客戶端發起連線,通過三次握手建立連線,用socket來進行通訊,通過輸入輸出流的方式來進行同步阻塞的通訊

每次客戶端發起連線請求,都會啟動一個執行緒

執行緒數量:客戶端併發訪問數為1:1,由於執行緒是JAVA虛擬機器中非常寶貴的資源,一旦執行緒數急劇增加,系統性能會急劇下降,導致執行緒棧溢位,建立新的執行緒失敗,並最終導致宕機

所以在JDK1.4之前,人們想到了一種方法,即PIO方式

2、PIO(偽非同步阻塞IO)

使用執行緒池來處理客戶端的請求

客戶端個數:執行緒池最大執行緒數=M:N,其中M遠大於N

在read和write的時候,還是IO阻塞的,只是把每個執行緒交由執行緒池來控制管理

3、NIO(非同步阻塞IO)

用NIO方式處理IO

使用多路複用器Selector來輪詢每個通道Channel,當通道中有事件時就通知處理,不會阻塞

使用相當複雜

4、AIO(真正的非同步非阻塞IO)

NIO2.0引入了新的非同步通道的概念,不需要使用多路複用器(Selector)對註冊通道進行輪詢即可實現非同步讀寫,從而簡化了NIO程式設計模型

使用Netty框架進行程式設計步驟

1、構建事件處理池

2、使用載入程式關聯事件處理池、通道、事件處理器

3、繫結埠服務

4、等待操作完成

5、關閉事件處理池

幾種IO的功能和特性對比


按照書上的例子碼了一遍:

服務端:

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class NettyServer {
	public void bind(int port) throws Exception {
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workGroup = new NioEventLoopGroup();
		try {
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workGroup).channel(NioServerSocketChannel.class)
					.option(ChannelOption.SO_BACKLOG, 1024)
					.childHandler(new ChildChannelHandler());
			// 繫結埠,同步等待成功
			ChannelFuture f = b.bind(port).sync();
			// 等待服務端監聽埠關閉
			f.channel().closeFuture().sync();
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			// 優雅退出,釋放執行緒池資源
			bossGroup.shutdownGracefully();
			workGroup.shutdownGracefully();
		}
	}

	private class ChildChannelHandler extends ChannelInitializer<SocketChannel> {
		@Override
		protected void initChannel(SocketChannel ch) throws Exception {
			ch.pipeline().addLast(new NettyServerHandle());
		}
	}

	public static void main(String[] args) throws Exception {
		int port = 8080;
		if (args != null && args.length > 0) {
			try {
				port = Integer.valueOf(args[0]);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		new NettyServer().bind(port);
	}
}
服務端處理器:
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

public class NettyServerHandle extends ChannelHandlerAdapter {
	public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {
		ByteBuf buf = (ByteBuf) msg;
		byte[] req = new byte[buf.readableBytes()];
		buf.readBytes(req);
		String body = new String(req, "UTF-8");
		System.out.println("The time server receive order:" + body);
		String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new java.util.Date(
				System.currentTimeMillis()).toString() : "BAD ORDER";
		ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
		ctx.write(resp);
	}

	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		ctx.flush();
	}

	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		ctx.close();
	}
}

客戶端:
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class NettyClient {
	public void connect(int port, String host) throws Exception {
		// 1、建立執行緒池
		EventLoopGroup group = new NioEventLoopGroup();
		try {
			// 2、使用引導器關聯執行緒池、通道、通達處理器、設定執行引數
			Bootstrap b = new Bootstrap();
			b.group(group).channel(NioSocketChannel.class)
					.option(ChannelOption.TCP_NODELAY, true)
					.handler(new ChannelInitializer<SocketChannel>() {
						@Override
						protected void initChannel(SocketChannel ch)
								throws Exception {
							ch.pipeline().addLast(new NettyClientHandle());
						}
					});
			// 發起非同步連線操作 3、繫結埠同步操作
			ChannelFuture f = b.connect(host, port).sync();
			// 4、監聽埠關閉
			f.channel().closeFuture().sync();
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			// 優雅退出,釋放NIO執行緒組 5、釋放資源
			group.shutdownGracefully();
		}
	}

	public static void main(String[] args) throws Exception {
		int port = 8080;
		if (args != null && args.length > 0) {
			try {
				port = Integer.valueOf(args[0]);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		new NettyClient().connect(port, "127.0.0.1");
	}
}

客戶端處理器:
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

import java.util.logging.Logger;

public class NettyClientHandle extends ChannelHandlerAdapter {
	private static final Logger logger = Logger
			.getLogger(NettyClientHandle.class.getName());
	private final ByteBuf firstMessage;

	public NettyClientHandle() {
		byte[] req = "QUERY TIME ORDER".getBytes();
		firstMessage = Unpooled.buffer(req.length);
		firstMessage.writeBytes(req);
	}

	public void channelActive(ChannelHandlerContext ctx) {
		ctx.writeAndFlush(firstMessage);
	}

	public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {
		ByteBuf buf = (ByteBuf) msg;
		byte[] req = new byte[buf.readableBytes()];
		buf.readBytes(req);
		String body = new String(req, "UTF-8");
		System.out.println("Now is:" + body);
	}

	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		// 釋放資源
		logger.warning("Unexpected exception from downstream:"
				+ cause.getMessage());
		ctx.close();
	}
}