java原生NIO SocketChannel不存在,调用Netty NioSocketChannel的disconnect(ChannelPromise promise) 时,会自动转换成close操作。
所以嘞,Channel中disconnect(ChannelPromise promise) 方法,是 Netty 为 UDP 设计的。
通过 NioSocketChannel中disconnect() 方法,应用程序里可以主动关闭 NioSocketChannel 通道,NioSocketChannel 继承 AbstractChannel 抽象类,所以 disconnect() 方法实际是 AbstractChannel 实现;在方法内部,会调用对应的 ChannelPipeline中disconnect() 方法,将 disconnect 事件在 pipeline 上传播。
@Override
public ChannelFuture disconnect() {
return pipeline.disconnect();
}
DefaultChannelPipeline中disconnect() 方法:
@Override
public final ChannelPipeline disconnect() {
tail.disconnect();
return this;
}
调用 TailContext的disconnect() 方法,将 flush 事件在 pipeline 中,从尾节点向头节点传播,TailContext 对 flush() 方法的实现,是从 AbstractChannelHandlerContext 抽象类继承,代码如下:
@Override
public ChannelFuture disconnect() {
return disconnect(newPromise());
}
@Override
public ChannelFuture disconnect(final ChannelPromise promise) {
// 判断是否为合法的 Promise 对象
if (isNotValidPromise(promise, false)) {
// cancelled
return promise;
}
final AbstractChannelHandlerContext next = findContextOutbound();
EventExecutor executor = next.executor();
if (executor.inEventLoop()) {
// <1> 如果没有 disconnect 操作,则执行 close 事件在 pipeline 上
// Translate disconnect to close if the channel has no notion of disconnect-reconnect.
// So far, UDP/IP is the only transport that has such behavior.
if (!channel().metadata().hasDisconnect()) {
next.invokeClose(promise);
// 如果有 disconnect 操作,则执行 disconnect 事件在 pipeline 上
} else {
next.invokeDisconnect(promise);
}
} else {
safeExecute(executor, new Runnable() {
@Override
public void run() {
// hasDisconnect() 方法,判断 Channel 是否支持 disconnect 操作,如果没有 disconnect 操作,则执行 close 事件在 pipeline 上
if (!channel().metadata().hasDisconnect()) {
next.invokeClose(promise);
// 如果有 disconnect 操作,则执行 disconnect 事件在 pipeline 上
} else {
next.invokeDisconnect(promise);
}
}
}, promise, null);
}
return promise;
}
嘿嘿快完了呢。