Netty 核心模块
Bootstrap 、ServerBootstrap
(1)Bootstrap意思是个引导,一个netty应用通常由一个Bootstrap开始,主
要作用是配置整个netty程序,串联各个组件,netty中Bootstrap类是客户端程
序启动引导类,ServerBootstrap是服务端启动引导类
(2)常见的方法有
- public ServerBootstrap group(EventLoopGroup parentGroup, EventLoopGroup childGroup) ,该方法用于服务端,用来设置两个EventLoop
- public B channel(Class<? extends C> channelClass) 该方法用来设置一个服务器通道实现
- public B option(ChannelOption option, T value) 用来给ServerChannel添加配置
- public ServerBootstrap childOption(ChannelOption childOption, T value) 用来给接收到的通道添加配置
- public ServerBootstrap childHandler(ChannelHandler childHandler) 用来设置业务处理类(自定义的handler)
- public ChannelFuture bind(int inetPort) 用于服务器端绑定端口号
- public ChannelFuture connect(String inetHost,int inetPort) 该方法用户客户端,用来连接服务端
Future. ChannelFuture
(1)Netty中所有的10操作都是异步的,不能立刻得知消息是否被正确处理。但是可以过一会等它执行売成或者亘接往册一个监听,具体的买现就是通过Future和ChannelFutures,他们可以注册一个监听,当操作执行成功或失败时监听会自动触发注册的监听事件
(2)常见的方法有
- Channelchannel(),返回当前正在进行I/O操作的通道
- ChannelFuture.sync(),等待异步操作执行完毕
Channel
(1) Netty 网络通信的组件,能够用于执行网络I/0 操作。
(2)通过Channel可获得当前网络连接的通道的状态
(3) 通过Channel可获得网络连接的配置参数(例如接收缓冲区大小)
(4) Channel 提供异步的网络I/O操作(如建立连接,读写,绑定端口),异步调
用意味着任何I/O调用都将立即返回,并且不保证在调用结束时所请求的I/0 操
作已完成
(5)调用立即返回一个ChannelFuture实例,通过注册监听器到ChannelFuture
上,可以I/O操作成功、失败或取消时回调通知调用方
(6)支持关联I/0操作与对应的处理程序
(7)不同协议、不同的阻塞类型的连接都有不同的Channel类型与之 对应,常
用的Channel类型:
-
NioSocketChannel, 异步的客户端TCP Socket连接。
-
NioServerSocketChannel, 异步的服务器端TCP Socket连接。
-
NioDatagramChannel, 异步的UDP连接。
-
NioSctpChannel, 异步的客户端Sctp连接。
-
NioSctpServerChannel, 异步的Sctp服务器端连接,这些通道涵盖了UDP
和TCP网络I/O以及文件I/O。
ChannelHandler及其实现类
(1) ChannelHandler是一 个接口,处理I/0事件或拦截I/0操作,并将其转发到
其ChannelPipeline(业务处理链)中的下一个处理程序。
(2)ChannelHandler 本身并没有提供很多方法,因为这个接口有许多的方法需
要实现,方便使用期间,可以继承它的子类
(3)ChannelHandler 及其实现类( 如 HttpServerHandler)
public class HttpServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
String str = " Hello world!";
byte[] bytes = str.getBytes();
ByteBuf byteBuf = Unpooled.wrappedBuffer(bytes);
FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, byteBuf);
//设置响应头
response.headers().set(CONTENT_TYPE, "text/plain");
response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
//写数据
ctx.write(response);
ctx.flush();
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
ctx.close();
}
}
ChannelInboundHandler用于处理入站I/O事件。(从管道里读数据)
ChannelOutboundHandler用于处理出站I/O操作。(往管道里写数据)
适配器
ChannelInboundHandlerAdapter用于处理入站I/O事件。(从管道里读数据)
ChannelOutboundHandlerAdapter用于处理出站I/O操作。(往管道里写数据)
ChannelDuplexHandler用于处理入站和出站事件。