Netty学习笔记(二)—— Channel

功能

Channel 是 Netty 网络操作抽象类,包括但不仅限于网络的读写、客户端建立和关闭连接、获取双方网络地址等。同时还包括 Netty 框架相关的功能,例如获取EventLoop、ByteBufAllocator、pipeline等。

接口

网络 I/O 操作

方法 功能
Channel read() 从当前的Channel中读取数据到第一个inbound缓冲区中,如果数据被成功读取,触发ChannelHandler.channelRead(ChannelHandlerContext,Object)事件。读取操作API调用完成后,紧接着会触发ChannelHander.channelReadConplete(ChannelHandlerContext)事件,这样业务的ChannelHandler可以决定是否需要继续读取数据。如果已经有操作请求被挂起,则后续的读操作会被忽略。
ChannelFuture write(Object msg) 请求将当前的msg写入到目标Channel中。注意,write操作只是将消息存入到消息发送环形数组中,并没有真正被发送,只有调用flush操作才会被写入到Channel中,发送给对方。
ChannelFuture write(Object msg, ChannelPromise promise ) 功能同上,添加了ChannelPromise参数负责设置写入操作结果。
Channel flush() 将消息发送给通信方。
ChannelFuture writeAndFlush(Object msg) 等价于方法2的加上flush() 操作。
ChannelFuture writeAndFlush(Object msg, ChannelPromise promise ) 等价于方法3的加上flush() 操作。
ChannelFuture close(ChannelPromise promise) 主动关闭当前连接,通过ChannelPromise设置操作结果并进行结果通知,无论操作是否成功,都可以通过ChannelPromise获取操作结果。该操作会级联触发ChannelPipeline中所有ChannelHandler的ChannelHandler.close(ChannelHandlerContext,ChannelPromise)事件。
ChannelFuture disconnect(ChannelPromise promise) 请求断开与远程通信对端的连接并使用ChannelPromise来获取操作结果的通知信息。该方法会级联触发ChannelPipeline中所有ChannelHandler的ChannelHandler.close(ChannelHandlerContext,ChannelPromise)事件。
ChannelFuture connect(SocketAddress remoteAddress) 客户端连接服务端,该方法会级联触发 ChannelHandler.connect(ChannelHandlerContext, SocketAddress, SocketAddress, ChannelPromise)
ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress) 功能同上但先绑定指定本地地址
ChannelFuture connect(SocketAddress remoteAddress, ChannelPromise promise) 添加ChannelPromise参数用于写入操作结果
ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) 先绑定本地地址
ChannelFuture bind(SocketAddress localAddress) 绑定本地Socket地址该方法级联触发ChannelHandler.bind(ChannelHandlerContext, SocketAddress, ChannelPromise)
ChannelFuture bind(SocketAddress localAddress, ChannelPromise promise) 添加ChannelPromise参数用于写入操作结果
ChnnelConfig config() 获取当前Channel的配置信息
boolean isOpen() 判断当前Channel是否已经打开
boolean isRegistered() 判断当前Channel是否已经注册到EventLoop上
boolean isActive() 判断当前Channel是否处于激活状态
ChannelMetadata metadata() 获取当前Channel的元数据描述信息,包括TCP参数配置等
SocketAddress localAddress() 获取当前Channel的本地绑定地址
SocketAddress remoteAddress() 获取当前Channel通信的远程Socket地址

其他

方法 功能
eventLoop() 获取Channel注册的EventLoop,即处理网络读写事件的Reactor线程
metadata() 当前Channel的TCP参数配置
parent() Channel对应的ServerSocketChannel
id() Channel的id

源码

猜你喜欢

转载自blog.csdn.net/qq_23016999/article/details/82144756