Netty Channel和ChannelFuture

Channel介绍

首先强调一点:NIO的Channel与Netty的Channel不是一个东西!
Netty重新设计了Channel接口,并且给予了很多不同的实现。Channel时Netty的网络抽象类,除了NIO中Channel所包含的网络I/O操作,主动建立/关闭连接,获取双方网络地址的功能外,还包含了Netty框架的功能,例如:获取Channel的EventLoop\Pipeline等。

Channel接口是能与一个网络套接字(或组件)进行I/0操作(读取\写入\连接\绑定)的纽带.
通过Channel可以获取连接的状态(是否连接/是否打开),配置通道的参数(设置缓冲区大小等),进行I/O操作
api文档
https://netty.io/4.1/api/io/netty/channel/Channel.html

当Channel完成工作后,需要调用ChannelOutboundInvoker.close()或ChannelOutboundInvoker.close(ChannelPromise)释放所有资源.这样做是为了确保所有资源(文件句柄)都能够得到释放

ChannelFuture接口

Netty API : 
The result of an asynchronous Channel I/O operation. 
All I/O operations in Netty are asynchronous. It means any I/O calls will return immediately with no guarantee that the requested I/O operation has been completed at the end of the call. Instead, you will be returned with a ChannelFuture instance which gives you the information about the result or status of the I/O operation.

由于Netty中的所有I / O操作都是异步的,因此Netty为了解决调用者如何获取异步操作结果的问题而专门设计了ChannelFuture接口.
因此,Channel与ChannelFuture可以说形影不离的.

api:https://netty.io/4.1/api/io/netty/channel/ChannelFuture.html

ChannelFuture的状态

Netty API : 
A ChannelFuture is either uncompleted or completed. When an I/O operation begins, a new future object is created. The new future is uncompleted initially - it is neither succeeded, failed, nor cancelled because the I/O operation is not finished yet. If the I/O operation is finished either successfully, with failure, or by cancellation, the future is marked as completed with more specific information, such as the cause of the failure. Please note that even failure and cancellation belong to the completed state.

ChannelFuture有两种状态:未完成(uncompleted)和完成(completed).
当令Channel开始一个I/O操作时,会创建一个新的ChannelFuture去异步完成操作.
被创建时的ChannelFuture处于uncompleted状态(非失败,非成功,非取消);一旦ChannelFuture完成I/O操作,ChannelFuture将处于completed状态,结果可能有三种:

  1. 操作成功
  2. 操作失败
  3. 操作被取消(I/O操作被主动终止)
    需要关注ChannelFuture的其它属性来获取异常信息。

ChannelFutureListener监听接口

ChannelFuture的get()方法获取异步操作的结果,但是切记一定要设置超时时间
Netty建议通过ChannelFutureListener接口执行异步操作结束后的回调.

api:https://netty.io/4.1/api/io/netty/util/concurrent/GenericFutureListener.html

示例代码:

 @Override
 public void channelRead(ChannelHandlerContext ctx, Object msg) {
     ChannelFuture future = ctx.channel().close();
     future.addListener(new ChannelFutureListener() {
         public void operationComplete(ChannelFuture future) {
             // Perform post-closure operation
             // ...
         }
     });
 }

另外,ChannelFuture允许添加一个或多个(移除一个或多个)ChannelFutureListener监听接口,方法名:addListener(), addListeners(), removeListener(), removeListeners()

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值