These two days to find the title of the example code, found that so many tutorials on the web, even how to achieve automatic re-connect do not speak, so write their own examples to paste up. Using recursion only, without multithreading, can achieve the initial goal:
Import Java.io.ioexception;import Java.net.connectexception;import Java.net.inetsocketaddress;import Java.nio.bytebuffer;import Java.nio.channels.selectionkey;import Java.nio.channels.selector;import Java.nio.channels.socketchannel;import Java.util.timer;public class Nioclient {//Channel selector private Selector selector;// The channel that communicates with the server Socketchannel socketchannel;//the IP address of the server to be connected private String hostip;//The remote server to be connected on the listening port private int Hostlistenningport;private static Boolean timetocken=false;private static timer timer = new Timer ();p rivate static Boolea N timerset=false;/** * Constructor * * @param hostip * @param hostlistenningport * @throws ioexception */public nioclient (String HostIP, int hostlistenningport) throws IOException {This.hostip = Hostip;this.hostlistenningport = HostListenningPort; Initialize ();} private void Initialize () throws IOException {//Open listening channel and set to non-blocking mode Try{socketchannel = Socketchannel.open (new Inetsocketaddress (Hostip,hostlistenningport));} catch (Connectexception e) {System.out.println ("Error happened when establishing connection, try again 5s later "); try {thread.sleep ()} catch (Interruptedexception E1) {E1 . Printstacktrace ();} if (!timerset) {timer.schedule (New Settocken (), 15000); timerset=true;} if (!timetocken) {initialize ();} return;} Socketchannel.configureblocking (false);//Open and register selector to channel Selector = Selector.open (); Socketchannel.register (Selector, Selectionkey.op_read);} /** * Send string to server * * @param message * @throws ioexception */public void sendmsg (String message) throws IOException {Bytebu Ffer WriteBuffer = Bytebuffer.wrap (Message.getbytes ("UTF-8")); Socketchannel.write (WriteBuffer);} public static void Main (string[] args) throws IOException {nioclient client = new Nioclient ("127.0.0.1", 12000); Client.sen Dmsg ("This is a nioclient, testing"); Client.end (); Timer.cancel ();} private void End () {//Todo auto-generated method stubtry {socketchannel.close ();} catch (IOException e) {//Todo Auto-gen Erated catch Blocke.printstacktrace ();}} Static class Settocken extends Java.util.TimerTaSK {@Overridepublic void run () {//TODO auto-generated method stubtimetocken=true;}}}
Java NIO Socketchannel Client Example (automatic reconnection after connection failure)