Netty Case, Intermediate Extension of Netty 4.1 Eight "Netty Heartbeat Service and Disconnected Reconnection"

Keywords: Netty Java network

Preamble Introduction

In our use of netty, we need to monitor whether the service is stable and can automatically reconnect when network abnormal links are broken.Need to implement listening; f.addListener(new MyChannelFutureListener())

Environmental preparation

1. jdk1.8 [below jdk1.7 can only partially support netty]
2. Netty4.1.36.Final [netty3.x 4.x 5 changes a lot each time, so does the interface class name]

Code Samples

itstack-demo-rpc-2-08
└── src
    └── main
    │    └── java
    │        └── org.itstack.demo.netty
    │             ├── client
    │             │   ├── MyChannelFutureListener.java
    │             │   ├── MyChannelInitializer.java
    │             │   ├── MyClientHandler.java
    │             │   └── NettyClient.java
    │             └── server
    │             	  ├── MyChannelInitializer.java
    │             	  ├── MyServerHandler.java
    │             	  └── NettyServer.java
    └── test
         └── java
             └── org.itstack.demo.test
                 ├── StartClient.java
                 └── StartServer.java

** Show some important code blocks, complete code can focus on public number acquisition; bugstack bug stack**

client/MyChannelFutureListener.java

/**
 * Hole stack: https://bugstack.cn
 * Public Number: bugstack wormhole stack  Get learning source 
 * Create by fuzhengwei on 2019
 */
public class MyChannelFutureListener implements ChannelFutureListener {
    @Override
    public void operationComplete(ChannelFuture channelFuture) throws Exception {
        if (channelFuture.isSuccess()) {
            System.out.println("itstack-demo-netty client start done. {Focus on Public Number: bugstack Bug hole stack, get source code}");
            return;
        }
        final EventLoop loop = channelFuture.channel().eventLoop();
        loop.schedule(new Runnable() {
            @Override
            public void run() {
                try {
                    new NettyClient().connect("127.0.0.1", 7397);
                    System.out.println("itstack-demo-netty client start done. {Focus on Public Number: bugstack Bug hole stack, get source code}");
                    Thread.sleep(500);
                } catch (Exception e){
                    System.out.println("itstack-demo-netty client start error go reconnect ... {Focus on Public Number: bugstack Bug hole stack, get source code}");
                }
            }
        }, 1L, TimeUnit.SECONDS);
    }
}

client/MyClientHandler.java

/**
 * Hole stack: https://bugstack.cn
 * Public Number: bugstack wormhole stack  Get learning source 
 * Create by fuzhengwei on 2019
 */
public class MyClientHandler extends ChannelInboundHandlerAdapter {

    /**
     * This channel is active when the client actively links the links on the server side.That is, the client establishes a communication channel with the server and can transfer data.
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        SocketChannel channel = (SocketChannel) ctx.channel();
        System.out.println("Link Report Start");
        System.out.println("Link Report Information: This client links to the server. channelId: " + channel.id());
        System.out.println("Link Report IP:" + channel.localAddress().getHostString());
        System.out.println("Link Report Port:" + channel.localAddress().getPort());
        System.out.println("Link report complete");
    }

    /**
     * This channel is inactive when the client actively disconnects the server.That is, the client and the server have closed the communication channel and cannot transfer data.
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("Disconnect Link Reconnect" + ctx.channel().localAddress().toString());
        //Disconnect during use
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    new NettyClient().connect("127.0.0.1", 7397);
                    System.out.println("itstack-demo-netty client start done. {Focus on Public Number: bugstack Bug hole stack, get source code}");
                    Thread.sleep(500);
                } catch (Exception e){
                    System.out.println("itstack-demo-netty client start error go reconnect ... {Focus on Public Number: bugstack Bug hole stack, get source code}");
                }
            }
        }).start();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //Receive msg messages {You no longer need to decode yourself here compared to the previous chapter}
        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " Received message:" + msg);
    }

    /**
     * Catch exceptions, and when they occur, you can do something about them, such as printing logs, closing links
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("Exception information, disconnect reconnect:\r\n" + cause.getMessage());
        ctx.close();
    }

}

client/NettyClient.java

/**
 * Hole stack: https://bugstack.cn
 * Public Number: bugstack wormhole stack  Get learning source 
 * Create by fuzhengwei on 2019
 */
public class NettyClient {

    public static void main(String[] args) {
        new NettyClient().connect("127.0.0.1", 7397);
    }

    public void connect(String inetHost, int inetPort) {
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(workerGroup);
            b.channel(NioSocketChannel.class);
            b.option(ChannelOption.AUTO_READ, true);
            b.handler(new MyChannelInitializer());
            ChannelFuture f = b.connect(inetHost, inetPort).sync();
            f.addListener(new MyChannelFutureListener()); //Add monitoring, process reconnection
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
        }
    }

}

server/MyServerHandler.java

/**
 * Hole stack: https://bugstack.cn
 * Public Number: bugstack wormhole stack  Get learning source 
 * Create by fuzhengwei on 2019
 */
public class MyServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        super.userEventTriggered(ctx, evt);
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent e = (IdleStateEvent) evt;
            if (e.state() == IdleState.READER_IDLE) {
                System.out.println("bugstack Cave stack reminder=> Reader Idle");
                ctx.writeAndFlush("Read Wait: Public Number bugstack Bug Hole Stack, Client Are you there[ctx.close()]{I end with a line break to handle half-packed stickers}... ...\r\n");
                ctx.close();
            } else if (e.state() == IdleState.WRITER_IDLE) {
                System.out.println("bugstack Cave stack reminder=> Write Idle");
                ctx.writeAndFlush("Write waiting: Public number bugstack Bug Hole Stack, Client Are you there{I end with a line break to handle half-packed stickers}... ...\r\n");
            } else if (e.state() == IdleState.ALL_IDLE) {
                System.out.println("bugstack Cave stack reminder=> All_IDLE");
                ctx.writeAndFlush("All Time: Public Number bugstack Bug Hole Stack, Client Are you there{I end with a line break to handle half-packed stickers}... ...\r\n");
            }
        }
        ctx.flush();
    }

    /**
     * This channel is active when the client actively links the links on the server side.That is, the client establishes a communication channel with the server and can transfer data.
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        SocketChannel channel = (SocketChannel) ctx.channel();
        System.out.println("Link Report Start");
        System.out.println("Link Report Information: A client is linked to this server");
        System.out.println("Link Report IP:" + channel.localAddress().getHostString());
        System.out.println("Link Report Port:" + channel.localAddress().getPort());
        System.out.println("Link report complete");
        //Notify client that the link was successfully established
        String str = "Notify client that the link was successfully established" + " " + new Date() + " " + channel.localAddress().getHostString() + "\r\n";
        ctx.writeAndFlush(str);
    }

    /**
     * This channel is inactive when the client actively disconnects the server.That is, the client and the server have closed the communication channel and cannot transfer data.
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("Client disconnects" + ctx.channel().localAddress().toString());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //Receive msg messages {You no longer need to decode yourself here compared to the previous chapter}
        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " Received message:" + msg);
        //Notify client chain that message sent successfully
        String str = "Server received:" + new Date() + " " + msg + "\r\n";
        ctx.writeAndFlush(str);
    }

    /**
     * Catch exceptions, and when they occur, you can do something about them, such as printing logs, closing links
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        System.out.println("Exception information:\r\n" + cause.getMessage());
    }

}

server/NettyServer.java

/**
 * Hole stack: https://bugstack.cn
 * Public Number: bugstack wormhole stack  Get learning source 
 * Create by fuzhengwei on 2019
 */
public class NettyServer {

    public static void main(String[] args) {
        new NettyServer().bing(7397);
    }

    private void bing(int port) {
        //Configure Server-side NIO Thread Group
        EventLoopGroup parentGroup = new NioEventLoopGroup(); //NioEventLoopGroup extends MultithreadEventLoopGroup Math.max(1, SystemPropertyUtil.getInt("io.netty.eventLoopThreads", NettyRuntime.availableProcessors() * 2));
        EventLoopGroup childGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(parentGroup, childGroup)
                    .channel(NioServerSocketChannel.class)    //Non-blocking mode
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childHandler(new MyChannelInitializer());
            ChannelFuture f = b.bind(port).sync();
            System.out.println("itstack-demo-netty server start done. {Focus on Public Number: bugstack Bug hole stack, get source code}");
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            childGroup.shutdownGracefully();
            parentGroup.shutdownGracefully();
        }

    }

}

test result

Start NettyServer * Set ctx.close() in your heart beat; simulate disconnection, wait for reconnection

itstack-demo-netty server start done. {Focus on public number: bugstack bug stack, get source code}
Link Report Start
 Link Report Information: A client is linked to this server
 Link Report IP:127.0.0.1
 Link Report Port:7397
 Link report complete
 bugstack bug stack reminder=> Reader Idle
 Client Disconnect/127.0.0.1:7397
 Link Report Start
 Link Report Information: A client is linked to this server
 Link Report IP:127.0.0.1
 Link Report Port:7397
 Link report complete
 bugstack bug stack reminder=> Reader Idle
 Client Disconnect/127.0.0.1:7397
 Link Report Start
 Link Report Information: A client is linked to this server
 Link Report IP:127.0.0.1
 Link Report Port:7397
 Link report complete
 bugstack bug stack reminder=> Reader Idle
 Client Disconnect/127.0.0.1:7397
 Link Report Start
 Link Report Information: A client is linked to this server
 Link Report IP:127.0.0.1
 Link Report Port:7397
 Link report complete
 Exception information:
The remote host forcibly closed an existing connection.
Client Disconnect/127.0.0.1:7397

Process finished with exit code -1

Start NettyClient

Link Report Start
 Link Report Information: This client links to the server.channelId:d9f3f045
 Link Report IP:127.0.0.1
 Link Report Port:53009
 Link report complete
 itstack-demo-netty client start done. {Focus on public number: bugstack bug stack, get source code}
2019-08-18 16:49:28 Received message: Notify client that link is successfully established Sun Aug 18 16:49:28 CST 2019 127.0.0.1
 2019-08-18 16:49:30 Received a message: Read Wait: bugstack bug stack public number, are you there [ctx.close()] {I end with a line break for half-pack glue}...
Disconnected Reconnection/127.0.0.1:53009
 Link Report Start
 Link Report Information: This client links to the server.channelId:23dc9235
 Link Report IP:127.0.0.1
 Link Report Port:53035
 Link report complete
 itstack-demo-netty client start done. {Focus on public number: bugstack bug stack, get source code}
2019-08-18 16:49:30 Received message: Notify client that link is successfully established Sun Aug 18 16:49:30 CST 2019 127.0.0.1
 2019-08-18 16:49:32 Received a message: Read Wait: Public Number bugstack wormhole stack, are you there [ctx.close()] {I end with a line break for half-pack glue}...
Disconnected Reconnect/127.0.0.1:53035
 itstack-demo-netty client start done. {Focus on public number: bugstack bug stack, get source code}
Link Report Start
 Link Report Information: This client links to the server.channelId:9c186f92
 Link Report IP:127.0.0.1
 Link Report Port:53052
 Link report complete
 itstack-demo-netty client start done. {Focus on public number: bugstack bug stack, get source code}
2019-08-18 16:49:32 Received message: Notify client that link is successfully established Sun Aug 18 16:49:32 CST 2019 127.0.0.1
 2019-08-18 16:49:34 Received a message: Read Wait: Public bugstack wormhole stack, are you there [ctx.close()] {I end with a line break for half-pack glue}...
Disconnected Reconnection/127.0.0.1:53052
 itstack-demo-netty client start done. {Focus on public number: bugstack bug stack, get source code}
Link Report Start
 Link Report Information: This client links to the server.channelId:46b1d56a
 Link Report IP:127.0.0.1
 Link Report Port:53069
 Link report complete
 itstack-demo-netty client start done. {Focus on public number: bugstack bug stack, get source code}
2019-08-18 16:49:34 Received message: Notify client that link is successfully established Sun Aug 18 16:49:34 CST 2019 127.0.0.1

Process finished with exit code -1

Posted by kidd1270 on Tue, 03 Sep 2019 18:17:15 -0700