Java.nio.channels-based programming practice-II.

Source: Internet
Author: User

Introduced

To provide concurrent processing efficiency, the user's request connection is randomly assigned to thread pool threads for processing, and HBase is also handling user requests in the same way

Client code can refer to: java.nio.channels-based programming practices-I.

Code
Import java.io.ioexception;import java.net.inetsocketaddress;import java.nio.bytebuffer;import  java.nio.channels.SelectionKey;import java.nio.channels.Selector;import  java.nio.channels.serversocketchannel;import java.nio.channels.socketchannel;import  java.util.iterator;import java.util.random;import java.util.set;import  java.util.concurrent.executorservice;import java.util.concurrent.executors;import  java.util.concurrent.timeunit;import org.apache.hadoop.util.stringutils;import org.slf4j.logger; Import org.slf4j.loggerfactory;import com.google.common.util.concurrent.threadfactorybuilder;public  class niosocketserver2 extends thread {private static final logger  log = loggerfactory.getlogger (niosocketserver2.class);p rivate static final  string charset =  "UTF-8";p rivate static final int buffer_size = 1024;private static final int FAIL_TRY_NUM = 3;private Selector  selector;private serversocketchannel ssc;private static niosocketserver2 server; Private reader[] readers = null;private random rand = new random ( );p rivate int readersize = 1;/** *  Program entry  *  *  @param   Args */public static void main (String[] args)  {server = new  NIOSocketServer2 (); Try {// server.setdaemon (true); Server.initserver (); Server.start ();}  catch  (exception e)  {e.printstacktrace ();//  If an exception occurs, close the client server.stopserver () directly; System.exit (1);}} @Overridepublic  void run ()  {int failNum = 0;while  (true)  {try { Int select = selector.select ();if  (select > 0)  {Set<SelectionKey>  keys = selecTor.selectedkeys (); Iterator<selectionkey> iter = keys.iterator ();while  (iter.hasNext ())  {selectionkey key = iter.next ();if  (Key.isacceptable ())  {doAcceptable (key); Iter.remove ();}}}  catch  (exception e)  {failNum++;if  (failnum > fail_try_num)  { Server.stopserver ();}}} /** *  Initialize server-side program, start listening ports  *  *  @throws  ioexception */private void  initserver ()  throws ioexception {selector = selector.open ();ssc =  Serversocketchannel.open (); ssc.configureblocking (false); Ssc.socket (). Bind (New inetsocketaddress (2181)); Ssc.register (selector, selectionkey.op_accept); Executorservice readpool = executors.newfixedthreadpool (readersize,new  Threadfactorybuilder (). Setnameformat ("rpcserver.reader=%d,port="  + 2181). SetDaemon (True). Build ()); readers = new reader[readersize];for  (int&Nbsp;i = 0; i < readersize; ++i)  {reader reader = new  reader (); Readers[i] = reader;readpool.execute (Reader);}} /** *  Stop server  *  *  @throws  IOException */private void  Stopserver ()  {try {if  (Selector != null && selector.isopen ())   {Selector.close ();} if  (Ssc != null && ssc.isopen ())  {ssc.close ();}}  catch  (ioexception e)  {log.info ("Shutdown Server failed:"  + e.getmessage ());}} Reader getreader ()  {return readers[rand.nextint (readersize)  % readers.length];} /** *  processing of new client connections  *  *  @param  key *  @throws  ioexception  */private void doacceptable (Selectionkey key)  throws ioexception { serversocketchannel server =  (Serversocketchannel)  key.channel (); socketchannel channel;while  ((Channel = server.accept ())  != null)  {try { Channel.configureblocking (false); Channel.socket (). Settcpnodelay (True); Channel.socket (). Setkeepalive (True);  catch  (Ioexception ioe)  {channel.close (); Throw ioe;} Reader reader = getreader (); Try {reader.startadd (); Selectionkey readkey = reader.registerchannel (channel);}  finally {reader.finishadd ();}}} /** *  Connected  *  *  @param  key */private void doconnectable ( Selectionkey key)  {log.info ("Connect is ok");} /** *  write message to client  *  *  @param  key *  @throws  ioexception */ Private void dowritemessage (Selectionkey key)  throws exception {socketchannel  sc =  (Socketchannel)  key.channel (); Bytebuffer buffer = bytebuffer.wrap ("Server write msg to&nbsP;client ". GetBytes (CHARSET));while  (Buffer.hasremaining ())  {sc.write (buffer); TimeUnit.SECONDS.sleep (1);} /** *  @param  key *  @throws  IOException */private void  Doreadmessage (Selectionkey key)  throws Exception {SocketChannel sc =  ( Socketchannel)  key.channel (); Bytebuffer bb = bytebuffer.allocate (buffer_size); Int read = sc.read (BB); while   (read > 0)  {bb.flip (); Byte[] barr = new byte[bb.limit ()];bb.get ( Barr); Log.info ("Server read msg from client:"  + new string (Barr, CHARSET)); Bb.clear (); Read = sc.read (BB);} TimeUnit.SECONDS.sleep (1);} private class reader implements runnable {private volatile boolean  adding = false;private final selector readselector; Reader ()  throws ioexception {this.readselector  = selector.open ();} Public void run ()  {try {dorunloop ();}  finally {try {readselector.close ();}  catch  (Ioexception ioe)  {log.error (GetName ()  +  ": error closing  read selector in  "+ getname (),  ioe);}}} Private synchronized void dorunloop ()  {while  (true)  {SelectionKey key  = null;try {readselector.select ();while  (adding)  {this.wait (1000);} Iterator<selectionkey> iter = readselector.selectedkeys (). Iterator ();while  ( Iter.hasnext ())  {key = iter.next (); Iter.remove ();if  (Key.isvalid ())  {if  ( Key.isreadable ())  {try {doreadmessage (key);}  catch  (exception e)  {e.printstacktrace ();}} if  (Key.iswritable ())  {try {dowritemessage (key);}  catch  (exception e)  {e.printstacktrace ();}} Key = null;}}  catch  (inTerruptedexception e)  {if  (True)  { // unexpected -- log  Itlog.info (GetName ()  +  ": unexpectedly interrupted: " +  Stringutils.stringifyexception (e));}}  catch  (Ioexception ex)  {log.error (GetName ()  +  ":  error in reader ",  ex);}}} /** * this gets reader into the state that waits for  The new channel to be * registered with readselector. if it  was waiting in select ()  the * thread will be woken up,  otherwise whenever select ()  is called it * will return even  if there is nothing to read and wait in * while (adding )  for finishadd call */public void startadd ()  {adding = true; Readselector.wakeup ();} Public synchronized selectionkey registerchannel (Socketchannel channel) throws  Ioexception {return channel.register (readselector, selectionkey.op_read| selectionkey.op_ WRITE);} Public synchronized void finishadd ()  {adding = false;this.notify ();}}


Java.nio.channels-based programming practice-II.

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.