Netty之Channel(五)disconnect操作

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;
}

嘿嘿快完了呢。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值