Netty Automatic re-connection

Source: Internet
Author: User
Tags creative commons attribution volatile

From: http://www.dozer.cc/2015/05/netty-auto-reconnect.html

Automatic re-connect

When you write Client and Server with Netty, you have to deal with automatic re-connection.

Server-side startup error, to continue to retry.

The client does not only handle the error at startup, but also handles a disconnected connection in the middle.

Server-side processing

Compared to regular code, the Server side can only handle one place:

 Public Final  class tcpserver {Private volatileEventloopgroup Bossgroup;Private volatileEventloopgroup Workergroup;Private volatileServerbootstrap Bootstrap;Private volatile Booleanclosed =false;Private Final intLocalPort;Public   tcpserver(int localport) { This. LocalPort = LocalPort; }Public   void close() {closed =true;         Bossgroup.shutdowngracefully ();          Workergroup.shutdowngracefully (); System.out.println ("Stopped Tcp Server:"+ LocalPort); }Public   void init() {closed =false; Bossgroup =NewNioeventloopgroup (); Workergroup =NewNioeventloopgroup (); Bootstrap =NewServerbootstrap ();          Bootstrap.group (Bossgroup, Workergroup);          Bootstrap.channel (Nioserversocketchannel.class); Bootstrap.childhandler (NewChannelinitializer<socketchannel> () {@Override              protected void initchannel(socketchannel ch) throws Exception{//todo:add More Handler}         });     Dobind (); } protected void dobind() {if(closed) {return; } bootstrap.bind (LocalPort). AddListener (NewChannelfuturelistener () {@Override             Public   void operationcomplete(channelfuture f) throws Exception {if(F.issuccess ()) {System.out.println ("Started Tcp Server:"+ LocalPort); }Else{System.out.println ("Started Tcp Server Failed:"+ LocalPort); F.channel (). EventLoop (). Schedule ((), Dobind (),1, timeunit.seconds);     }             }         }); } }

We have divided the entire initialization into two parts, the first part is the initialization of the relevant class, the second part of the real listening port.

The most special place here is the callbindmethod, add alistenerThe check is successful, and if it fails, it needs to be called.channel().eventLoop().schedule()method to create a task that I set for this code is 1 seconds after attempting to reconnect.

Also, consider that the server can be artificially shut down, so you need to check that the current time is closed. If you don't check it, your server may never be able to shut down.

Client-side processing

The client-side startup process is similar, but requires a handler to handle the disconnection.

 Public  class TcpClient {Private volatileEventloopgroup Workergroup;Private volatileBootstrap Bootstrap;Private volatile Booleanclosed =false;Private FinalString RemoteHost;Private Final intRemotePort;Public   TcpClient(String remotehost, int remoteport) { This. remotehost = RemoteHost; This. RemotePort = RemotePort; }Public   void close() {closed =true;         Workergroup.shutdowngracefully (); System.out.println ("Stopped Tcp Client:"+ Getserverinfo ()); }Public   void init() {closed =false; Workergroup =NewNioeventloopgroup (); Bootstrap =NewBootstrap ();         Bootstrap.group (Workergroup);          Bootstrap.channel (Niosocketchannel.class); Bootstrap.handler (NewChannelinitializer<socketchannel> () {@Override             Public   void initchannel(socketchannel ch) throws Exception{Channelpipeline pipeline = Ch.pipeline (); Pipeline.addfirst (NewChannelinboundhandleradapter () {@Override                     Public   void channelinactive(channelhandlercontext ctx) throws Exception{Super. channelinactive (CTX); Ctx.channel (). EventLoop (). Schedule ((), Doconnect (),1, timeunit.seconds); }                 });//todo:add More Handler}         });     Doconnect (); } private void doconnect() {if(closed) {return; } channelfuture future = Bootstrap.connect (NewInetsocketaddress (RemoteHost, RemotePort)); Future.addlistener (NewChannelfuturelistener () {Public   void operationcomplete(channelfuture f) throws Exception {if(F.issuccess ()) {System.out.println ("Started Tcp Client:"+ Getserverinfo ()); }Else{System.out.println ("Started Tcp Client Failed:"+ Getserverinfo ()); F.channel (). EventLoop (). Schedule ((), Doconnect (),1, timeunit.seconds);     }             }         }); } Private String getserverinfo() {returnString.Format ("remotehost=%s remoteport=%d", RemotePort, RemotePort); } }

As you can see, we channelInactive also created a task in the event to reconnect after 1 seconds.

Sample code

You can run and see for yourself:

Https://github.com/dozer47528/AutoReconnectNettyExample

This work was created by Dozer and licensed under the Creative Commons Attribution-NonCommercial use of 4.0 international license agreements.

Netty Automatic re-connection

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.