Netty:使用`IdleStateHandler`来检测断开连接

时间:2017-12-03 07:03:55

标签: java android netty

我阅读了IdleStateHandler的文档,从我的服务器中我实现了与文档相同的文档, 但我不知道如何确切地判断客户端是否断开连接,例如客户端失去了Wifi连接。

根据我的理解,在我的处理程序中,当客户端断开连接时,方法channelInactive()被触发, 然后使用IdleStateHandler,当在指定的时间段内未执行任何读取时,将触发IdleState.READER_IDLE, 然后在没有从客户端读取3秒后我关闭了频道,并期待channelInactive将被触发但是不是,为什么?。

初始化程序

public class ServerInitializer extends ChannelInitializer<SocketChannel> {

    String TAG = "LOG: ";
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        System.out.println(TAG + "Starting ServerInitializer class...");
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast("decoder", new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
        pipeline.addLast("encoder", new ObjectEncoder());
        pipeline.addLast("idleStateHandler", new IdleStateHandler(6, 3, 0, TimeUnit.SECONDS));
        pipeline.addLast("handler", new ServerHandler());
    }
}

处理程序

public class ServerHandler extends ChannelInboundHandlerAdapter {

    private String TAG = "LOG: ";

    public ServerHandler(){}

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        Log.w(TAG,"New Client become connected, Sending a message to the Client. Client Socket is: " + ctx.channel().remoteAddress().toString());

        List<String> msg = new ArrayList<>();
        msg.add(0,"sample message 1");
        msg.add(1,"sample message 2");
        sendMessage(ctx, msg);
    }

    public void sendMessage(ChannelHandlerContext ctx, List message){
        ctx.write(message);
        ctx.flush();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        Log.w(TAG,"A Client become disconnected. Client Socket is: " + ctx.channel().remoteAddress().toString() + " id: " + (String.valueOf(ctx.channel().hashCode())));
         //COnnection id dead, do something here...
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object object) { // (2)
        Log.w(TAG, "CLIENT: "+ ctx.channel().remoteAddress().toString() + " SAYS: " + object);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (4)
        // Close the connection for that client  when an exception is raised.
        Log.e(TAG,"Something's wrong, CLIENT: "+ ctx.channel().remoteAddress().toString() + " CAUSE: " + cause.toString());
        ctx.close();
    }


    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        Log.w(TAG,"LOLO");
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent e = (IdleStateEvent) evt;
            if (e.state() == IdleState.READER_IDLE) {

                ctx.close(); //Closed the Channel so that the `channelInactive` will be trigger

            } else if (e.state() == IdleState.WRITER_IDLE) {

                ctx.writeAndFlush("ping\n"); //Send ping to client

            }
        }

    }
}

任何人都可以帮助我

2 个答案:

答案 0 :(得分:2)

IdleStateHandler应始终是您管道中的第一个处理程序。

答案 1 :(得分:0)

使用ReadTimeoutHandler而不是IdleStateHandler并覆盖exceptionCaught方法。