为什么80%的码农都做不了架构师?>>>   

Netty提供了应用启动的配置跟启动API,服务端:ServerBootstarp,客户端Bootstarp。

他们用来指定

EventLoopGroup

Channel

ChannelOptions

当Channel注册时,调用ChannelHandler

设置Attributes到指定Chanel。

绑定IP跟端口

ServerBootstarp绑定端口使用bind()。Bootstarp连接使用connect()。

关系:

客户端Bootstarp提供了以下方法:

group(..) : 设置EventLoopGroup,用于服务Channel中I/O操作

channel(..) 、channelFacotry(..) :  指定使用Channel。 NIO/OIO...

localAddress(...) :设置本地地址,端口

option(...) : 设置Channel的配置

attr(..) : 设置Channel的附加属性

handler(..) : 设置定义的ChannelHandler到ChannelPipeline中

clone() : 拷贝。

remoteAddress() : 设置远程连接地址,端口

connect() : 连接远程服务

bind()    : 绑定本地服务

Bootstarp,bind()创建Channel后,调用connect(),将会建立连接与Channel()绑定。

若直接调用,则创建Channel 与建立的连接绑定。

Bootstrap bootstrap = new Bootstrap(); #1
bootstrap.group(new NioEventLoopGroup()) #2
.channel(NioSocketChannel.class) #3
.handler(new SimpleChannelInboundHandler<ByteBuf>() { #4
@Override
protected void channeRead0(
ChannelHandlerContext channelHandlerContext,
ByteBuf byteBuf) throws Exception {
System.out.println("Reveived data");
byteBuf.clear();
}
});
ChannelFuture future = bootstrap.connect(
new InetSocketAddress("www.manning.com", 80)); #5
future.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture channelFuture)
throws Exception {
if (channelFuture.isSuccess()) {
System.out.println("Connection established");
} else {
System.err.println("Connection attempt failed");
channelFuture.cause().printStackTrace();
}
}
});

注意:使用NioSocketChannel,则要与NioEventLoopGourp结对绑定,否则报错,OIO同理。

服务端ServerBootstrap
group(..) : 设置EventLoopGroup,用于服务ServerChannel的I/O操作与接收Channels

channel(..)、channelFacotry : 设置ServerChannel

localAddress(...) : 设置ServerChannel绑定地址与端口

option(...) : 设置ServerChannel的配置

childOption(...) : 设置ServerChannel accept 并创建的 Channel的配置

attr(...)    : 设置ServerChannel的额外属性

childAttr(...) : 设置ServerChannel accept 并创建的  Channel的额外属性

handler(...) : ServerChannel的ChannelHandler,有默认实现,无特别需求不指定

childHandler(...) : 设置由ServerChanel accpet到创建的Chanel的ChannelHandler,每个ChannelHandler 对应的处理不同客户端I/O

clone()    : 拷贝

bind(...) : 绑定并启动服务。返回ChannelFutrue。

ServerBootstrap bootstrap = new ServerBootstrap(); #1
bootstrap.group(new NioEventLoopGroup(), new NioEventLoopGroup()) #2
.channel(NioServerSocketChannel.class) #3
.childHandler(new SimpleChannelInboundHandler<ByteBuf>() { #4
@Override
protected void channelRead0(ChannelHandlerContext ctx,
ByteBuf byteBuf) throws Exception {
System.out.println("Reveived data");
byteBuf.clear();
}
});
ChannelFuture future = bootstrap.bind(new InetSocketAddress(8080)); #5
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();
}
}
});

ServerBootstarp内嵌Bootstarp连接,共同EventLoop例子,使用场景,做代理,或服务端需要连接其他服务来获取数据处理。

ServerBootstrap bootstrap = new ServerBootstrap(); #1
bootstrap.group(new NioEventLoopGroup(), new NioEventLoopGroup()) #2
.channel(NioServerSocketChannel.class) #3
.childHandler(new SimpleChannelInboundHandler<ByteBuf>() { #4
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 Exception {
System.out.println("Reveived data");
in.clear();
}
});
bootstrap.group(ctx.channel().eventLoop()); #8
connectFuture = bootstrap.connect(
new InetSocketAddress("www.manning.com", 80)); #9
}
@Override
protected void channelRead0(ChannelHandlerContext
channelHandlerContext, ByteBuf byteBuf) throws 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();
}
}
});

ServerBootstarp 需要支持多种协议。我们需要加入多个ChannelHandler时候,使用继承ChannelInitializer,并实现initChannel方法,便可以把 Channel加入到ChanelPipeline中,并且与EventLoopGroup关联。例子:

ServerBootstrap bootstrap = new ServerBootstrap(); #1
bootstrap.group(new NioEventLoopGroup(), new NioEventLoopGroup()) #2
.channel(NioServerSocketChannel.class) #3
.childHandler(new ChannelInitializerImpl()); #4
ChannelFuture future = bootstrap.bind(new InetSocketAddress(8080)); #5
future.sync();
final class ChannelInitializerImpl extends ChannelInitializer<Channel> {#6
@Override
protected void initChannel(Channel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline(); #7
pipeline.addLast(new HttpClientCodec());
pipeline.addLast(new HttpObjectAggregator(Integer.MAX_VALUE));
}
}

ChannelOptions and attributes

channelOptions 可以设置 Channel的连接超时,keep-alive等

attributes 可以设置一些用户自定义的值。

final AttributeKey<Integer> id = new AttributeKey<Integer>("ID"); #1
Bootstrap bootstrap = new Bootstrap(); #2
bootstrap.group(new NioEventLoopGroup()) #3
.channel(NioSocketChannel.class) #4
.handler(new SimpleChannelInboundHandler<ByteBuf>() #5
@Override
public void channelRegistered(ChannelHandlerContext ctx)
throws Exception {
Integer idValue = ctx.channel().attr(id).get(); #6
// do something with the idValue
}
@Override
protected void channelRead0(
ChannelHandlerContext channelHandlerContext,
ByteBuf byteBuf) throws Exception {
System.out.println("Reveived data");
byteBuf.clear();
}
});
bootstrap.option(ChannelOption.SO_KEEPALIVE,true)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000); #7
bootstrap.attr(id, 123456); #8
ChannelFuture future = bootstrap.connect(
new InetSocketAddress("www.manning.com", 80)); #9
future.syncUninterruptibly();

使用UDP协议,跟Bootstarp有一点不同的是,不需要bind() 或 connect() 操作

Bootstrap bootstrap = new Bootstrap();
bootstrap.group(new OioEventLoopGroup()).channel(OioDatagramChannel.class)
.handler(new SimpleChannelInboundHandler<DatagramPacket>(){
@Override
public void channelRead0(ChannelHandlerContext ctx,
DatagramPacket msg) throws Exception {
// Do something with the packet
}
});
ChannelFuture future = bootstrap.bind(new InetSocketAddress(0));
future.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture channelFuture)
throws Exception {
if (channelFuture.isSuccess()) {
System.out.println("Channel bound");
} else {
System.err.println("Bound attempt failed");
channelFuture.cause().printStackTrace();
}
}
});

转载于:https://my.oschina.net/XzhiF/blog/265584

Netty笔记(八) Bootstrap相关推荐

  1. ReactJS学习笔记八:动画

    ReactJS学习笔记八:动画 分类: react学习笔记 javascript2015-07-06 20:27 321人阅读 评论(0) 收藏 举报 react动画 目录(?)[+] 这里只讨论Re ...

  2. 【opencv学习笔记八】创建TrackBar轨迹条

    createTrackbar这个函数我们以后会经常用到,它创建一个可以调整数值的轨迹条,并将轨迹条附加到指定的窗口上,使用起来很方便.首先大家要记住,它往往会和一个回调函数配合起来使用.先看下他的函数 ...

  3. 吴恩达《机器学习》学习笔记八——逻辑回归(多分类)代码

    吴恩达<机器学习>笔记八--逻辑回归(多分类)代码 导入模块及加载数据 sigmoid函数与假设函数 代价函数 梯度下降 一对多分类 预测验证 课程链接:https://www.bilib ...

  4. python3.4学习笔记(八) Python第三方库安装与使用,包管理工具解惑

    python3.4学习笔记(八) Python第三方库安装与使用,包管理工具解惑 许多人在安装Python第三方库的时候, 经常会为一个问题困扰:到底应该下载什么格式的文件? 当我们点开下载页时, 一 ...

  5. 前端学习笔记:Bootstrap框架入门

    前端学习笔记:Bootstrap框架入门 一.Bootstrap概述 1.基本信息 ​Bootstrap,来自 Twitter,是目前很受欢迎的前端框架.Bootstrap 是基于 HTML.CSS. ...

  6. ROS学习笔记八:创建ROS msg和srv

    ROS学习笔记八:创建ROS msg和srv 本节主要讲述了如何创建和建立ROS msg和srv,同时使用命令行工具rosmsg.rossrv和roscp. msg和srv简介 msg:描述ROS m ...

  7. 《MFC游戏开发》笔记八 游戏特效的实现(二):粒子系统

    本系列文章由七十一雾央编写,转载请注明出处. http://blog.csdn.net/u011371356/article/details/9360993 作者:七十一雾央 新浪微博:http:// ...

  8. Halcon 学习笔记八:颜色识别

    Halcon 学习笔记八:颜色识别 一.图像处理需要的知识 二.图像处理的预处理和分割过程 二.颜色识别的方法 三.例子一 四.例子二 五.例子三 一.图像处理需要的知识 1.图像处理基础(rgb(h ...

  9. ZooKeeper学习笔记(八):ZooKeeper集群写数据原理

    写数据原理 写流程直接请求发送给Leader节点 这里假设集群中有三个zookeeper服务端 ACK (Acknowledge character)即是确认字符,在数据通信中,接收站发给发送站的一种 ...

  10. TCPIP详解Protocol 读书笔记(八) Traceroute程序

    TCP/IP详解:Protocol 读书笔记(八) Chapter8 Traceroute程序 文章目录 TCP/IP详解:Protocol 读书笔记(八) Chapter8 Traceroute程序 ...

最新文章

  1. 程序员的自我修养之马桶修理工:compose方法的妙用!
  2. 算法工程师掌握了这个炼丹技巧的我开始突飞猛进
  3. Replace Pioneer
  4. css版式_第2部分:使版式具有响应能力,并为以后的版本奠定基础
  5. 抱歉,请不要把 “业务逻辑层” 理解为 “业务中台”
  6. P4161-[SCOI2009]游戏【dp】
  7. linux下得到date命令,linux下date命令获得今天日期的用法
  8. 唯美红色圣诞节背景素材,节日气氛尽显
  9. 计算机理论python字符串作业_[Python基础 ] Day_07_作业参考答案
  10. Server-U文件名中文乱码问题解决方法
  11. paip.php 配置ZEND DEBUGGER 断点调试for cli..
  12. 阿里代码规范检查工具的安装使用以及阿里代码格式化
  13. STM32控制WS2812B HAL库
  14. Excel-图表与文本框/图片的组合
  15. 青云诀2显示登录服务器超时,青云诀2游戏突然显示数据包损坏怎么办 解决方案分享...
  16. tmp文件删除会影响计算机吗,电脑临时文件能删吗?
  17. jetson nano 5 运行YOLOV5
  18. c语言中的格式化字符串
  19. BMP格式详解<转>
  20. GD32F4xx串口收发,DMA+空闲中断

热门文章

  1. centos安装cowboy过程
  2. [译] 写给前端开发者的 GraphQL 指南
  3. 关于写代码的几个看法
  4. Maven的配置以及Eclipse的设置
  5. redis(二)redis实战 使用redis进行文章的排序
  6. Metasploit(一)--Meterpreter的命令速查表
  7. 文件翻译002片:Process Monitor帮助文档(Part 2)
  8. 【转载】Real6410 Linux 常见问题总结(截至2010/07/26)
  9. wince中的hook(钩子)用法
  10. [J2SE 基础知识]2、抽象类和接口(上)