Netty中的Channel,是对网络通信信道的抽象。官方解释如下:
A nexus to a network socket or a component which is capable of I/O operations such as read, write, connect, and bind.
大致含义是:能够执行read、write、connect和bind操作网络套接字或组件的链接。也就是说,Channel的两头都是网络套接字。
Netty中Channel相关接口如下:
首先可以看到Channel继承了ChannelOutboundInvoker接口。bound,边界之意。ChannelOutboundInvoker,顾名思义,对Channel与外部进行交互的操作进行了抽象。
接口中方法归纳如下:
//将channel绑定到本地的SocketAddress
ChannelFuture bind(SocketAddress localAddress);
//将channle连接到远程的SocketAddress
ChannelFuture connect(SocketAddress remoteAddress);
//将channel绑定到本地的SocketAddress,同时将channle连接到远程的SocketAddress
ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress);
//断开channel与远端的连接
ChannelFuture disconnect();
//关闭channle
ChannelFuture close();
每一个Channel都会指定一个ChannelPipeline,并在创建新Channel时自动创建。为了进一步介绍Channel,我们需要先了解一下ChannelPipeline。
对于ChannelPipeline,官方解释如下:
A list of ChannelHandlers which handles or intercepts inbound events and outbound operations of a Channel. ChannelPipeline implements an advanced form of the Intercepting Filter pattern to give a user full control over how an event is handled and how the ChannelHandlers in a pipeline interact with each other.
大致含义是:处理或拦截一个Channel的inbound事件和outbound操作的一系列ChannelHandler。ChannelPipeline实现了 Intercepting Filter 模式的高级形式,让用户完全控制如何处理事件以及管道中的ChannelHandler如何相互交互。