Netty timeout mechanism and implementation of heartbeat program

Source: Internet
Author: User

This article describes the principle of the Netty timeout mechanism and how to send a heartbeat to maintain the connection when the connection is idle.

Introduction to the Netty timeout mechanism

The Netty timeout type idlestate is mainly divided into:

    • All_idle: No data received or sent over time
    • Reader_idle: No data received over time
    • Writer_idle: No data sent over time

Under Netty's timeout package, the main classes are:

    • Idlestateevent: Timed-out event
    • Idlestatehandler: Timeout Status processing
    • Readtimeouthandler: Read Timeout status processing
    • Writetimeouthandler: Write timeout status processing

where Idlestatehandler contains read \ Write timeout status processing, such as

 private static final int read_idel_time_out = 4; //Read timeout private static final int write_idel_time_out = 5; //write timeout private static final int all_idel_time_out = 7; //all timeouts new Idlestatehandler (Read_idel_time_out, WRITE_IDEL_TIME_OUT, ALL_ Idel_time_out, timeunit.seconds));  

In the example above, the read timeout defined in Idlestatehandler is 4 seconds, the write timeout is 5 seconds, and all other timeouts are 7 seconds.

Application Idlestatehandler

Since Idlestatehandler includes read \ Write timeout status processing, many times Readtimeouthandler, Writetimeouthandler can be used. Define another channelinitializer named Heartbeathandlerinitializer:

PublicClassHeartbeathandlerinitializerExtendschannelinitializer<channel> {PrivateStaticFinalint read_idel_time_out =4;Read timeoutPrivateStaticFinalint write_idel_time_out =5; //write timeout private static final int all_idel_time_out = 7; //all timeouts  @Override  protected void initchannel (Channel CH) throws Exception {channelpipeline pipeline = Ch.pipeline (); Pipeline.addlast (new Idlestatehandler (Read_idel_time_out, Write_idel_time_out, ALL_IDEL_TIME_OUT, Timeunit.seconds)); //1 pipeline.addlast (new Heartbeatserverhandler ()); //2}}             
    1. Use Idlestatehandler to set the time for read and write timeouts
    2. Defines a Heartbeatserverhandler processor that is used to handle timeouts when the heartbeat is sent
Defines a heartbeat processor
PublicClassHeartbeatserverhandlerExtendsChannelinboundhandleradapter {Return a unreleasable view on the given bytebufWhich'll just ignore release and retain calls.PrivateStaticFinal Bytebuf heartbeat_sequence = unpooled. Unreleasablebuffer (Unpooled.copiedbuffer ("Heartbeat", Charsetutil.utf_8));1@OverridePublicvoidUsereventtriggered(Channelhandlercontext ctx, Object evt)Throws Exception {if (evtInstanceof Idlestateevent) {//2 idlestateevent event = (idlestateevent) evt; String type = if (event.state () = = Idlestate.reader_idle) {type =  "read IDLE";} else if (event.state () = = Idlestate.writer_idle) {type =  "write idle"; } else if (event.state () = = Idlestate.all_idle) {type =  "all idle"; } ctx.writeandflush (Heartbeat_sequence.duplicate ()). AddListener (Channelfuturelistener.close_on_failure); //3 System.out.println (Ctx.channel (). remoteaddress () + " Timeout type: "+ type"; } else {super.usereventtriggered (CTX, evt);}}}   
    1. What to send when a heartbeat is defined
    2. Determine if it is a idlestateevent event, and then handle
    3. Send heartbeat content to client
Server

Server code is simple and listens on port 8082 after startup

PublicFinalClassHeartbeatserver {StaticFinalint PORT =8082;PublicStaticvoidMain(string[] args)Throws Exception {Configure the server. Eventloopgroup Bossgroup =New Nioeventloopgroup (1); Eventloopgroup Workergroup = new Nioeventloopgroup (); try {serverbootstrap b = new Serverbootstrap (); B.group (Bossgroup, Workergroup). Channel ( nioserversocketchannel.class). Option (Channeloption.so_backlog, + ). Handler (new Logginghandler ( Loglevel.info). Childhandler (new Heartbeathandlerinitializer ()); //Start the server. Channelfuture f = b.bind (PORT). sync (); //Wait until the server socket is closed. F.channel (). Closefuture (). sync (); finally { //Shut down all event loops to terminate all threads. bossgroup.shutdowngracefully (); Workergroup.shut Downgracefully (); } }}
Client Testing

The client uses the Telnet program that comes with the operating system:

telnet 127.0.0.1 8082
Effect

Transfer from Http://waylau.com/netty-time-out-and-heartbeat/?utm_source=tuicool&utm_medium=referral

Netty timeout mechanism and implementation of heartbeat program

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.