博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
(转)socket Aio demo
阅读量:5010 次
发布时间:2019-06-12

本文共 3988 字,大约阅读时间需要 13 分钟。

原文地址:

参考文档:

aio(或者叫nio2 ?) jdk1.7的新特性,代码上比nio写着舒服,但是性能貌似没比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();    }    @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
(){ @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

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

 

转载于:https://www.cnblogs.com/kevin1990/p/6249189.html

你可能感兴趣的文章
android之android.intent.category.DEFAULT的用途和使用
查看>>
CAGradientLayer 透明渐变注意地方(原创)
查看>>
织梦DEDE多选项筛选_联动筛选功能的实现_二次开发
查看>>
iOS关于RunLoop和Timer
查看>>
SQL处理层次型数据的策略对比:Adjacency list vs. nested sets: MySQL【转载】
查看>>
已存在同名的数据库,或指定的文件无法打开或位于 UNC 共享目录中。
查看>>
MySQL的随机数函数rand()的使用技巧
查看>>
thymeleaf+bootstrap,onclick传参实现模态框中遇到的错误
查看>>
python字符串实战
查看>>
wyh的物品(二分)
查看>>
12: xlrd 处理Excel文件
查看>>
综合练习:词频统计
查看>>
中文url编码乱码问题归纳整理一
查看>>
Cesium应用篇:3控件(3)SelectionIndicator& InfoBox
查看>>
58. Length of Last Word(js)
查看>>
前端面试题汇总(持续更新...)
查看>>
如何成为F1车手?
查看>>
QT自定义消息
查看>>
Save (Not Permitted) Dialog Box
查看>>
装饰模式(Decorator)
查看>>