Netty学习(五)BootStrap详解

1.Bootstrap 类型

Netty 的包括两种不同类型的引导。而不仅仅是当作的“服务器”和“客户”的引导,更有用的是考虑他 们的目的是支持的应用程序功能。

2.引导客户端和无连接协议

当需要引导客户端或一些无连接协议时,需要使用Bootstrap类。

 

1. 创建一个新的 Bootstrap 来创建和连接到新的客户端管道

2. 指定 EventLoopGroup

3. 指定 Channel 实现来使用

4. 设置处理器给 Channel 的事件和数据

5. 连接到远端主机

EventLoop 和 EventLoopGroup 记住,EventLoop 分配给该 Channel 负责处理 Channel 的所有操作。当你执行一个方法,该方法返回一个 ChannelFuture ,它将在 分配给 Channel 的 EventLoop 执行。 EventLoopGroup 包含许多 EventLoops 和分配一个 EventLoop 通道时注册。 

3.引导服务器

服务器的引导共用了客户端引导的一些逻辑。


		 
		 ServerBootstrap bootstrap = new ServerBootstrap(); //1
		 
		 bootstrap.group(new NioEventLoopGroup(), //2
		 new NioEventLoopGroup()).channel(NioServerSocketChannel.class) //3
		 .childHandler( //4
		 new SimpleChannelInboundHandler<ByteBuf>() {
		 ChannelFuture connectFuture;
		 @Override
		 public void channelActive(ChannelHandlerContext ctx) throws Exception {
		 Bootstrap bootstrap = new Bootstrap();//5
		 bootstrap.channel(NioSocketChannel.class) //6
		 .handler(new SimpleChannelInboundHandler<ByteBuf>() { //7
		 @Override
		 protected void channelRead0(ChannelHandlerContext ctx, ByteBuf in) throws E
		 xception {
		 System.out.println("Reveived data");
		 }
		 });
		 bootstrap.group(ctx.channel().eventLoop()); //8
		 connectFuture = bootstrap.connect(new InetSocketAddress("www.manning.com", 80)); //9
		 }
		 @Override
		 protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) t
		 hrows Exception {
		 if (connectFuture.isDone()) {
		 // do something with the data //10
		 }
		 }
		 });
		 ChannelFuture future = bootstrap.bind(new InetSocketAddress(8080)); //11
		 future.addListener(new ChannelFutureListener() {
		 @Override
		 public void operationComplete(ChannelFuture channelFuture) throws Exception {
		 if (channelFuture.isSuccess()) {
		 System.out.println("Server bound");
		 } else {
		 System.err.println("Bound attempt failed");
		 channelFuture.cause().printStackTrace();
		 }
		 }
		 });
	 

 1. 创建一个新的 ServerBootstrap 来创建新的 SocketChannel 管道并且绑定他们 2. 指定 EventLoopGroups 从 ServerChannel 和接收到的管道来注册并获取 EventLoops 3. 指定 Channel 类来使用 4. 设置处理器用于处理接收到的管道的 I/O 和数据 5. 创建一个新的 Bootstrap 来连接到远程主机 6. 设置管道类 7. 设置处理器来处理 I/O 8. 使用相同的 EventLoop 作为分配到接收的管道 9. 连接到远端 10. 连接完成处理业务逻辑 (比如, proxy) 11. 通过配置了的 Bootstrap 来绑定到管道

4.在一个引导中添加多个 ChannelHandler

在所有的例子代码中,我们在引导过程中通过 handler() 或childHandler() 都只添加了一个 ChannelHandler 实例,对于简单的程序可能足够,但是对于复杂的程序则无法满足需求。例如,某个程 序必须支持多个协议,如 HTTP、WebSocket。若在一个 ChannelHandle r中处理这些协议将导致一个 庞大而复杂的 ChannelHandler。Netty 通过添加多个 ChannelHandler,从而使每个 ChannelHandler 分工明确,结构清晰。

猜你喜欢

转载自blog.csdn.net/zzqtty/article/details/81097770