netty heartbeat detection mechanism

Posted by yendor on Tue, 11 Feb 2020 16:11:16 +0100

There is a heartbeat detection mechanism in Netty. When the client does not read or write for a certain period of time, the server can detect it and prompt
IdleStateHandler is the processor that netty processes idle state

The specific implementation steps are as follows:
1. Reader idletime: indicates how long it is not read, a heartbeat detection packet will be sent to check whether it is connected
2. Writer idletime: indicates how long it is not written, a heartbeat detection packet will be sent to check whether it is connected
3.allIdleTime: indicates how long it takes not to read or write, a heartbeat detection packet will be sent to check whether it is connected
4. when there is free time, the IdleStateEvent event will be triggered
5. When the IdleStateEvent is triggered, it will be passed to the next handler of the pipeline for processing. When the event is triggered by a callback, the next handler's usereventtiggled will be processed in this method when the IdleStateEvent (read idle, write idle, read write idle)
Code to implement the server:

package com.jym.heart;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

/**
 * @program: NettyPro
 * @description: Heartbeat detection
 * @author: jym
 * @create: 2020/02/10
 */
public class JymHeartServer {
    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup,workerGroup).channel(NioServerSocketChannel.class)
                    // Add log processor in bossGroup
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .option(ChannelOption.SO_BACKLOG,128)
                    .childOption(ChannelOption.SO_KEEPALIVE,true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            // Join the idlestadehandler provided by netty
                            /**
                             IdleStateHandler Is the netty processor that handles idle state
                             1.readerIdleTime : Indicates how long it has not been read, a heartbeat detection packet will be sent to check whether it is connected
                             2.writerIdleTime : Indicates how long it has not been written, a heartbeat detection packet will be sent to check whether it is connected
                             3.allIdleTime : Indicates how long it takes not to read or write, a heartbeat packet will be sent to check whether it is connected
                             4.When idle, the IdleStateEvent event event will be triggered
                             5.When the IdleStateEvent is triggered, it will be passed to the next handler of the pipeline for processing,
                                Triggered by a callback, the next handler's usereventtriggered will handle the IdleStateEvent in this method
                             */
                            pipeline.addLast(new IdleStateHandler(3,5,7, TimeUnit.SECONDS));
                            // Add a custom handler for further processing of idle detection
                            pipeline.addLast(new JymHeartServerHandler());
                        }
                    });

            System.out.println("Server started");
            ChannelFuture sync = serverBootstrap.bind(9000).sync();
            sync.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }
}

Custom processor:

package com.jym.heart;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * @program: NettyPro
 * @description:
 * @author: jym
 * @create: 2020/02/10
 */
public class JymHeartServerHandler extends ChannelInboundHandlerAdapter {
    /**
     *
     * @param ctx context
     * @param evt Event
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if(evt instanceof IdleStateEvent){
            // Transforming evt down to IdleStateEvent
            IdleStateEvent event = (IdleStateEvent)evt;
            String eventType = null;
            switch (event.state()) {
                case ALL_IDLE:
                    eventType = "Read free";
                    break;
                case READER_IDLE:
                    eventType = "Write idle";
                    break;
                case WRITER_IDLE:
                    eventType = "Read and write idle";
                    break;
            }
            System.out.println(ctx.channel().remoteAddress()+"----Timeout event occurs----"+eventType);
        }
    }
}

Lack of years of study, knowledge is too shallow, please forgive me for saying wrong.

There are 10 kinds of people in the world, one is binary, the other is not binary.

74 original articles published, 54 praised, 440000 visitors+
Private letter follow

Topics: Netty socket Java