当客户端关闭或在 netty 中失去互联网连接时,如何检测客户端在服务器上的断开连接

How to detect client's disconnect at server when client power off or lost internet connection in netty

我想在客户端关闭或失去互联网连接时检测客户端在服务器上的断开连接,并从列表客户端中删除。我可以吗?

我正在尝试一些问题,但它不起作用。 这是我的代码:

final ChannelFuture cf = chc.channel().writeAndFlush(new TextWebSocketFrame(dataSend));
            cf.addListener(new GenericFutureListener<Future<? super Void>>() {

                public void operationComplete(Future<? super Void> f) throws Exception {

                    if (!cf.isSuccess()) {

                        ServerHandler.agentChannelList.get(tranfer.getUsername()).remove(chc);
                        if (ServerHandler.agentChannelList.get(tranfer.getUsername()).isEmpty()) {
                            if (ServerHandler.agentOnlineQueue.containsKey(tranfer.getPage_id())) {
                                ServerHandler.agentOnlineQueue.get(tranfer.getPage_id()).remove(tranfer.getUsername());
                            }
                        }
                    }
                }

            });

唯一的 "real" 解决方案是在您的协议中实现类似 "ping/pong" 的东西。基本上你写入远程对等点,如果写入失败或者远程对等点没有响应,你会认为它已经死了。