简体   繁体   中英

Netty client send keep alive to server

I want to write keep alive command from client to server using Netty. I found out that option of IdleStateHandler . I dont know how to solve the problem in the client side, this is my code:

public void connect() {
    workerGroup = new NioEventLoopGroup();
    Bootstrap bs = new Bootstrap();
    bs.group(workerGroup).channel(NioSocketChannel.class);
    bs.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast("idleStateHandler", new IdleStateHandler(0, 0, 300));
            ch.pipeline().addLast("logger", new LoggingHandler());
            ch.pipeline().addLast("commandDecoder", new CuCommandDecoder());
            ch.pipeline().addLast("commandEncoder", new CuCommandEncoder());
        }
    });

After add IdleStateHandler to channel. Where the handling code should be? Did it new method that implements IdleStateHandler ?

According to the JavaDoc, IdleStateHandler will generate new events according to the current status of the channel:

  • IdleState#READER_IDLE for timeout on Read operation
  • IdleState#WRITER_IDLE for timeout on Write operation
  • IdleState#ALL_IDLE for timeout on both Read/Write operation

Then you need to implement in you handlers the handling of those events as (example taken from documentation from here ):

// Handler should handle the IdleStateEvent triggered by IdleStateHandler.
public class MyHandler extends ChannelDuplexHandler {
   @Override
   public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
       if (evt instanceof IdleStateEvent) {
           IdleStateEvent e = (IdleStateEvent) evt;
           if (e.state() == IdleState.READER_IDLE) {
               ctx.close();
           } else if (e.state() == IdleState.WRITER_IDLE) {
               ctx.writeAndFlush(new PingMessage());
           }
       }
   }
}

Here the example will close on first READ idle, and try to send a ping in Write idle. One could implement also the "pong" response, and also changing the read part to a ping request too... The way you want to handle your keep-alive being related to your protocol.

This could be done both on client and server side.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM