[Java]socket Aio demo

参考文档:html

http://my.oschina.net/u/862897/blog/164425java

http://my.oschina.net/cshbbrain/blog/87076 linux

http://my.oschina.net/bluesky0leon/blog/132361 ios

http://blog.csdn.net/caiwenfeng_for_23/article/details/8458299 shell



aio(或者叫nio2 ?) jdk1.7的新特性,代码上比nio写着舒服,可是性能貌似没比nio强。。。apache

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();
	}

	@Override
	public 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>(){
				@Override
				public void completed(AsynchronousSocketChannel result,
						Object attachment) {
					assc.accept(null, this);
					handler(result,attachment);
				}

				@Override
				public void failed(Throwable exc, Object attachment) {
					exc.printStackTrace();
				}								
			});
			
			synchronized(lock){			
				lock.wait();
			}
			channelGroup.shutdownNow();
			logger.info("aioserver 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 server :"+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(); //清空buff数据
			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 windows

static void t3(){		
		AioServer aiose = new AioServer(9777);
		//线程模式启动
		new Thread(aiose).start();;		
		//非线程模式启动
//		aiose.run();
		try {
			Thread.sleep(1000*60*5);
			//3秒后关闭
			aiose.shutdown();
		} catch (InterruptedException e) {		
			e.printStackTrace();
		}
	}


run.shjsp

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.jar
cp=$cp:log4j-1.2.16.jar

echo java $jopts -cp $cp AioTest1
java $jopts -cp $cp AioTest1

注:这个run.sh的内容是java开启nio那抄过来的,对aio来讲貌似没用,由于linux下aio原本就是Epoll实现。ide

aio在windows下采用IOCP实现。性能



apache ab压力结果:

D:\tools\Apache2.2\bin>ab -n 1000 -c 50 http://192.168.2.183:9777/q.jsp?q=1
This 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 requests
Completed 200 requests
Completed 300 requests
Completed 400 requests
Completed 500 requests
Completed 600 requests
Completed 700 requests
Completed 800 requests
Completed 900 requests
Completed 1000 requests
Finished 1000 requests


Server Software:
Server Hostname:        192.168.2.183
Server Port:            9777

Document Path:          /
Document Length:        0 bytes

Concurrency Level:      50
Time taken for tests:   1.078 seconds
Complete requests:      1000
Failed requests:        0
Write errors:           0
Total transferred:      5000 bytes
HTML transferred:       0 bytes
Requests 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] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    1   3.1      0      16
Processing:     0   51  37.6     31     188
Waiting:        0   35  41.4     31     188
Total:          0   52  37.6     31     188

Percentage 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)


象这种helloword,nio的“Requests per second”通常在1500左右。。。

相关文章
相关标签/搜索