在ChannelGroup中检测通道连接是否关闭

时间:2019-04-08 12:04:39

标签: netty

根据此代码(来自netty示例),我要实现状态系统。所以我需要检测客户端连接何时丢失(例如,由于客户端互联网捆绑已完成)

public class SecureChatServerHandler extends SimpleChannelInboundHandler<String> {

    static final ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    public void channelActive(final ChannelHandlerContext ctx) {
        ctx.pipeline().get(SslHandler.class).handshakeFuture().addListener(
                new GenericFutureListener<Future<Channel>>() {
                    @Override
                    public void operationComplete(Future<Channel> future) throws Exception {
                        ctx.writeAndFlush(
                                "Welcome to " + InetAddress.getLocalHost().getHostName() + " secure chat service!\n");
                        ctx.writeAndFlush(
                                "Your session is protected by " +
                                        ctx.pipeline().get(SslHandler.class).engine().getSession().getCipherSuite() +
                                        " cipher suite.\n");

                        channels.add(ctx.channel());
                    }
        });
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        // Send the received message to all channels but the current one.
        for (Channel c: channels) {
            if (c != ctx.channel()) {
                c.writeAndFlush("[" + ctx.channel().remoteAddress() + "] " + msg + '\n');
            } else {
                c.writeAndFlush("[you] " + msg + '\n');
            }
        }

        // Close the connection if the client has sent 'bye'.
        if ("bye".equals(msg.toLowerCase())) {
            ctx.close();
        }
    }

    ---
}

如何在频道关闭时通知频道组?

示例来源:https://netty.io/4.1/xref/io/netty/example/securechat/SecureChatServerHandler.html

1 个答案:

答案 0 :(得分:1)

解决此问题的一种方法是在处理程序中使用channelInactive函数。

通过成功关闭或网络错误关闭通道时,将调用此函数。

@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    // Send the received message to all channels but the current one.
    for (Channel c: channels) {
        if (c != ctx.channel()) {
            c.writeAndFlush("[" + ctx.channel().remoteAddress() + "] has left the chat\n");
        }
    }
}