[Java]socket Aio Demo

Source: Internet
Author: User

Jdk1.7 's new features, the code is more comfortable than NIO, but the performance seems to be no stronger than nio ...

import java.net.inetsocketaddress;import java.nio.bytebuffer;import  java.nio.channels.asynchronouschannelgroup;import java.nio.channels.asynchronousserversocketchannel; Import java.nio.channels.asynchronoussocketchannel;import java.nio.channels.completionhandler;import  java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import  org.apache.log4j.logger;public class aioserver implements runnable{final static  Logger logger = logger.getlogger (Aioserver.class); Object lock = new object ( ); inetsocketaddress serveraddress = null;int backlog = 0;int buff_size  = 1024;int threadpoolsize = 0;public aioserver (Int port) { This.serveraddress = new inetsocketaddress (port); initialization ();} Public aioserver (string ip,int port) {This.serveraddress = new inetsocketadDress (ip,port); initialization ();} Void initialization () {threadpoolsize = threadpoolsize>0? threadpoolsize:  Runtime.getruntime (). Availableprocessors ();} @Overridepublic  void run ()  {try {logger.info ("Aioserver threadpoolsize:" + This.threadpoolsize); Executorservice threadpool = executors.newfixedthreadpool (this.threadpoolsize);  Asynchronouschannelgroup channelgroup = asynchronouschannelgroup.withthreadpool (ThreadPool); Final asynchronousserversocketchannel assc = asynchronousserversocketchannel.open ( Channelgroup); if (this.backlog>0) { assc.bind (Serveraddress,this.backlog); }else {  Assc.bind (serveraddress);  }logger.info ("Aioserver listen:" +this.serveraddress); Assc.accept (NULL,  new CompletionHandler<AsynchronousSocketChannel,Object> () {@Overridepublic  void  Completed (asynchronoussocketchannel result,object attachment)  {Assc.accept (null, this); handler (result,attachment);} @Overridepublic  void failed (throwable exc, object attachment)  { Exc.printstacktrace ();}}); Synchronized (lock) {lock.wait ();} Channelgroup.shutdownnow (); Logger.info ("AIOSERVER&NBSP;SHUTDOWNC.");  catch  (exception e)  {e.printstacktrace ();}} static byte[] echo =  "Done." GetBytes (); Static int conncount = 1;void handler (Asynchronoussocketchannel conn, Object att) {try{//logger.info ("CONNECT&NBSP;SERVER&NBSP;:" +conncount++); Bytebuffer buff = bytebuffer.allocate (this.buff_size); Buff.clear ();int rl =  Conn.read (Buff). get (); Buff.flip (); Logger.info ("recv " +rl+ ": " +new string (Buff.array (), 0,RL)); Buff.clear ();  //empties the Buff Data buff.put (echo); Buff.flip (); Int wl = conn.write (Buff). get (); Logger.info ("send " +WL); Conn.close ();} catch (Exception ex) {ex.printstacktrace ();}} Public voiD setthreadpoolsize (int threadpoolsize) {this.threadpoolsize = threadpoolsize;} Public void setbacklog (Int backlog) {this.backlog = backlog;} Public void shutdown () {//logger.info ("Call shutdown ()"), synchronized (lock) {Lock.notifyall ();}}}


Aiotest1.java

static void T3 () {Aioserver aiose = new Aioserver (9777);//thread mode starts the new thread (Aiose). Start ();; /non-threaded mode boot//aiose.run (); try {thread.sleep (1000*60*5);//3 seconds to close Aiose.shutdown ();} catch (Interruptedexception e) { E.printstacktrace ();}}


run.sh

jopts= '-dcom.sun.management.jmxremote.port=8999 ' jopts= $jopts '-dcom.sun.management.jmxremote.authenticate=false ' jopts= $jopts '-dcom.sun.management.jmxremote.ssl=false ' jopts= $jopts '-djava.nio.channels.spi.selectorprovider= Sun.nio.ch.EPollSelectorProvider ' cp=aio.jarcp= $cp: Log4j-1.2.16.jarecho java $jopts-cp $cp aiotest1java $jopts-cp $CP AioTest1


Apache AB pressure results:

D:\tools\apache2.2\bin>ab -n 1000 -c 50 http://192.168.2.183:9777/q.jsp?q=1this  is ApacheBench, Version 2.3 < $Revision:  655654 $>copyright 1996  Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/Licensed to  the apache software foundation, http://www.apache.org/benchmarking 192.168.2.183   (be patient) completed 100 requestscompleted 200 requestscompleted 300  requestsCompleted 400 requestsCompleted 500 requestsCompleted 600  requestscompleted 700 requestscompleted 800 requestscompleted 900  requestscompleted 1000 requestsfinished 1000 requestsserver software:server  hostname:        192.168.2.183server port:             9777document path:          /document length:         0 bytesConcurrency Level:       50time taken for tests:   1.078 secondscomplete requests:       1000Failed requests:         0write errors:           0total transferred:       5000 bytesHTML transferred:        0 bytesRequests per second:    927.54 [#/sec]  (mean) time  per request:       53.906 [ms]  (mean) time per  request:       1.078 [ms]  (mean, across all  concurrent requests) Transfer rate:          4.53 [kbytes/sec]  receivedconnection times  (MS)                min  mean[+/-sd] median   maxConnect:         0    1   3.1      0       16Processing:     0   51   37.6     31     188Waiting:         0   35  41.4     31      188total:          0   52   37.6     31     188percentage of the  requests served within a certain time  (MS)   50%     31  66%      47  75%     47  80%      63  90%    141  95%    156   98%    172  99%    172 100%    188   (Longest request)


Like this Helloword,nio "requests per second" is generally around 1500 ...

[Java]socket Aio Demo

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.