Netty4学习笔记(8)-- Channel接口

Channel接口

Channel是Netty4最核心的接口之一,拥有将近40个方法和一个内部接口。本文将对Channel接口的众多方法做一个归类和总结,为进一步研究Channel实现做准备。Channel继承了AttributeMap接口,关于AttributeMap的详细介绍请看上一篇文章。

public interface Channel extends AttributeMap, Comparable<Channel> {
   ...
}

类似getter的方法

SocketAddress localAddress();
SocketAddress remoteAddress();
ChannelConfig config();
ChannelMetadata metadata();
Channel parent();
EventLoop eventLoop();
ChannelPipeline pipeline();
ByteBufAllocator alloc();
Unsafe unsafe();

这一组方法最容易理解:

  • localAddress()返回channel绑定的本地地址,remoteAddress()返回与Channel连接的远程地址
  • config()返回一个ChannelConfig对象,通过这个对象可以配置Channel相关的参数
  • metadata()返回一个ChannelMetadata对象,通过这个对象可以查询具体的Channel实现是否支持某种操作。目前ChannelMetadata只有一个方法,hasDisconnect(),用来查询Channel实现是否支持disconnect()操作。
  • parent()方法返回一个Channel的父Channel。按照Javadoc的说法,视Channel如何被创建而定,Channel可能会有一个父Channel。比如说如果一个SocketChannel是被ServerSocketChannel创建(accept)的,那么调用SocketChannel的parent()方法就会返回这个ServerSocketChannel
  • eventLoop()方法返回Channel注册到了哪个EventLoop里
  • pipeline()方法返回Channel的Pipeline
  • alloc()方法返回与Channel关联的ByteBufAllocator实例
  • unsafe()方法返回一个Unsafe实例。这个Unsafe实例只供Channel实现内部使用

状态查询方法

boolean isOpen();
boolean isRegistered();
boolean isActive();
boolean isWritable(); 

这组方法用于查询Channel的当前状态。isWritable()方法比较有误导性,看起来好像是说Channel是否是可写,但实际是查询写操作是否可以立即被IO线程处理。其余三个方法将在后面的文章里详细分析。


Future相关方法

ChannelFuture closeFuture();
ChannelPromise voidPromise();
ChannelPromise newPromise();
ChannelProgressivePromise newProgressivePromise();
ChannelFuture newSucceededFuture();
ChannelFuture newFailedFuture(Throwable cause);

这组方法其实又可以分为两种,closeFuture()voidPromise()可以算作getter方法,剩下四个以new开头的方法是工厂方法。


事件触发方法

ChannelFuture bind(SocketAddress localAddress);
ChannelFuture bind(SocketAddress localAddress, ChannelPromise promise);
ChannelFuture connect(SocketAddress remoteAddress);
ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress);
ChannelFuture connect(SocketAddress remoteAddress, ChannelPromise promise);
ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise);
ChannelFuture disconnect();
ChannelFuture disconnect(ChannelPromise promise);
ChannelFuture close();
ChannelFuture close(ChannelPromise promise);

Channel read();
ChannelFuture write(Object msg);
ChannelFuture write(Object msg, ChannelPromise promise);
Channel flush();
ChannelFuture writeAndFlush(Object msg, ChannelPromise promise);
ChannelFuture writeAndFlush(Object msg);

这组方法会触发I/O事件,这些事件会通过ChannelPipeline被ChannelHandler处理。要想知道事件如何在Pipeline里传播,请看这篇文章。


Unsafe接口

Unsafe接口是Channel的一个内部接口,我没弄明白这个接口的设计意图,暂时只能根据接口名和Javadoc的说明得出以下结论:

  • Unsafe接口仅供Netty内部使用,任何方法都不应该被user调用,甚至这个接口都不应该被user知道

你可能感兴趣的:(Netty4学习笔记(8)-- Channel接口)