Java Socket NIO Programming

Source: Internet
Author: User
Tags dateformat

The last time I wrote a socket BASIC programming, but there is a problem, blocking is particularly serious, so small made up to find the NIO study a bit ...

 1  public  class   Timeserver { 2  3  public  static  void   Main (string[] args) { 4  Multipexertimese RVer timersserver=new  multipexertimeserver ("192.168.1.102", 8400); 5  new  Thread (timersserver, "nio-multiplexer" Span style= "color: #000000;" >). Start ();  6   7  8 } 

1  Public classMultipexertimeserverImplementsRunnable {2 3     PrivateSelector Selector;4     5     PrivateServersocketchannel Serversocketchannel;6     7     Private volatile Booleanstop;8     9      PublicMultipexertimeserver (String addr,intPoint ) {Ten         Try { OneSelector=Selector.open (); AServersocketchannel=Serversocketchannel.open (); -Serversocketchannel.socket (). Bind (Newinetsocketaddress (addr, point)); -Serversocketchannel.configureblocking (false); the Serversocketchannel.register (selector, selectionkey.op_accept); -SYSTEM.OUT.PRINTLN ("Socket server:" +serversocketchannel.socket (). Getinetaddress () + ":" +serversocketchannel.socket () . Getlocalport () + ""); -}Catch(Exception e) { - e.printstacktrace (); +System.exit (1); -         } +     } A      at      Public voidStop () { -          This. stop=true; -     } -      - @Override -      Public voidrun () { in          while(!stop) { -             Try { toSelector.select (1000); +Set<selectionkey> selectionkeys=Selector.selectedkeys (); -                 if(Selectionkeys! =NULL&& selectionkeys.size () >0){ theIterator<selectionkey> it=selectionkeys.iterator (); *Selectionkey key=NULL; $                      while(It.hasnext ()) {Panax Notoginsengkey=It.next (); - It.remove (); the                         Try { + handleinput (key); A}Catch(Exception e) { the                             if(key!=NULL){ + Key.cancel (); -                                 if(Key.channel ()! =NULL){ $                                     Try { $ Key.channel (). Close (); -}Catch(Exception E1) { - e1.printstacktrace (); the                                     } -                                 }Wuyi                             } the                         } -                     } Wu                 } -}Catch(Exception e) { About e.printstacktrace (); $             } -         } -         if(selector!=NULL){ -             Try { A selector.close (); +}Catch(Exception e) { the e.printstacktrace (); -             } $         } the     } the  the     Private voidHandleinput (Selectionkey key)throwsioexception{ the         if(Key.isvalid ()) { -             //request to process new Access in             if(Key.isacceptable ()) { theServersocketchannel ssc=(Serversocketchannel) Key.channel (); theSocketchannel sc=ssc.accept (); AboutSc.configureblocking (false); the Sc.register (selector,selectionkey.op_read); theSocketAddress clientaddress =sc.getremoteaddress ();  theSYSTEM.OUT.PRINTLN ("Socket link New client:" +clientaddress);  +             } -             if(Key.isreadable ()) { the                 //reading DataBayiSocketchannel sc=(Socketchannel) Key.channel (); theBytebuffer Readbuffer=bytebuffer.allocate (1024); the                 intreadbytes=Sc.read (readbuffer); -                 if(readbytes>0){ - Readbuffer.flip (); the                     byte[] bytes=New byte[Readbuffer.remaining ()]; the readbuffer.get (bytes); theString body=NewString (Bytes, charset.forname ("GBK")); theSocketAddress clientaddress =sc.getremoteaddress ();  -SYSTEM.OUT.PRINTLN ("Socket link Old client:" +clientaddress);  theSYSTEM.OUT.PRINTLN ("Server receives data:" +body); the                     //and write the data back to the client. theSimpleDateFormat dateformat=NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");94String Time=dateformat.format (NewDate ()); theString res= "from the service side of the response, Time:" +Time ; the Dowrite (sc,res); the}Else if(readbytes<0){98 Key.cancel (); About sc.close (); -}Else{101                     //System.out.println ("The server received 0 bytes of data ...");102                 }103             }104         } the     }106     107     Private voidDowrite (Socketchannel sc,string Res)throwsioexception{108         if(res!=NULL&& Res.trim (). Length () >0){109             byte[] bytes=res.getbytes (); theBytebuffer Bytebuffer=bytebuffer.allocate (1024);111 bytebuffer.put (bytes); the Bytebuffer.flip ();113 Sc.write (bytebuffer); the         } the     } the     

The code doesn't want to explain too much, and it's time to sort out the basic concepts of NIO ...

Java Socket NIO Programming

Related Article

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.