欢迎来到天天文库
浏览记录
ID:14239802
大小:46.00 KB
页数:22页
时间:2018-07-27
《通过java nio实现socket服务器与客户端功能》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、通过JAVANIO实现Socket服务器与客户端功能importjava.util.concurrent.ArrayBlockingQueue; importjava.util.concurrent.ConcurrentHashMap; importjava.util.concurrent.ThreadPoolExecutor; importjava.util.concurrent.TimeUnit; publicclassServer{ privateSelectorselector=getSelector(); privateS
2、erverSocketChannelss=null; privatestaticThreadPoolExecutorthreadPool=newThreadPoolExecutor(10,10,500,TimeUnit.MILLISECONDS, newArrayBlockingQueueRunnable(20)); privatestaticMapInteger,SelectionKeyselectionKeyMap=newConcurrentHashMap(); publicSelectorgetSelector(){ try{
3、 returnSelector.open(); }catch(IOExceptione){ e.printStackTrace(); returnnull; *创建非阻塞服务器绑定5555端口 publicServer(){ try{ ss=ServerSocketChannel.open(); ss.bind(newInetSocketAddress(5555)); ss.configureBlocking(false); if(selector==null){ selector=Selector.open(); ss.regis
4、ter(selector,SelectionKey.OP_ACCEPT); }catch(Exceptione){ e.printStackTrace(); close(); *关闭服务器 privatevoidclose(){ threadPool.shutdown(); try{ if(ss!=null){ ss.close(); if(selector!=null){ selector.close(); }catch(IOExceptione){ e.printStackTrace(); *启动选择器监听客户端事件 priva
5、tevoidstart(){ threadPool.execute(newRunnable(){ @Override publicvoidrun(){ try{ while(true){ if(selector.select(10)==0){ continue; IteratorSelectionKeyiterator=selector.selectedKeys().iterator(); while(iterator.hasNext()){ SelectionKeyselectedKey=iterator.next(); iter
6、ator.remove(); try{ if(selectedKey.isReadable()){ if(selectionKeyMap.get(selectedKey.hashCode())!=selectedKey){ selectionKeyMap.put(selectedKey.hashCode(),selectedKey); threadPool.execute(newReadClientSocketHandler(selectedKey)); }elseif(selectedKey.isWritable()){ Obje
7、ctresponseMessage=selectedKey.attachment(); SocketChannelserverSocketChannel=(SocketChannel)selectedKey.channel(); selectedKey.interestOps(SelectionKey.OP_READ); if(responseMessage!=null){ threadPool.execute(newWriteClientSocketHandler(serverSocketChannel, responseMess
8、age)); }elseif(selectedKey.isAcceptable()){ ServerSocketChannelssc=(ServerSocketChannel)selectedKey.channel(); Socket
此文档下载收益归作者所有