检测ChannelGroup中的通道连接关闭

问题描述 投票:1回答:1

根据这段代码(来自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();
        }
    }

    ---
}

how to notify the group of channels when a channel is closed ?

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

netty
1个回答
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");
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.