亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用nio 中 selectionKey.isReadable()造成 死循環

使用nio 中 selectionKey.isReadable()造成 死循環

慕粉4241372 2018-08-09 14:01:17
@Test public?void?clientSocket()?throws?IOException?{ ????SocketChannel?socketChannel?=?SocketChannel.open(new?InetSocketAddress("localhost",?9999)); ????socketChannel.configureBlocking(false); ????ByteBuffer?byteBuffer?=?ByteBuffer.allocate(1024); ????byteBuffer.put("你好好好好".getBytes()); ????byteBuffer.flip(); ????socketChannel.write(byteBuffer); ????byteBuffer.clear(); ????socketChannel.shutdownOutput(); ????socketChannel.close(); } @Test public?void?serverSocket()?throws?IOException?{ ????ServerSocketChannel?serverSocketChannel?=?ServerSocketChannel.open(); ????serverSocketChannel.configureBlocking(false); ????serverSocketChannel.bind(new?InetSocketAddress(9999)); ????Selector?selector?=?Selector.open(); ????//?注冊連接事件 ????serverSocketChannel.register(selector,?SelectionKey.OP_ACCEPT); ????while?(selector.select()?>?0)?{ ????????Set<SelectionKey>?selectionKeySet?=?selector.selectedKeys(); ????????System.out.println(selectionKeySet.size()); ????????Iterator<SelectionKey>?iterator?=?selectionKeySet.iterator(); ????????while?(iterator.hasNext())?{ ????????????SelectionKey?selectionKey?=?iterator.next(); ????????????if?(selectionKey.isAcceptable())?{ ????????????????System.out.println("accept====="); ????????????????SocketChannel?socketChannel?=?serverSocketChannel.accept(); ????????????????socketChannel.configureBlocking(false); ????????????????socketChannel.register(selector,?SelectionKey.OP_READ); ????????????}?else?if?(selectionKey.isReadable())?{ ???????????????????? ????????????????System.out.println("read====="); ????????????????SocketChannel?socketChannel?=?(SocketChannel)?selectionKey.channel(); ????????????????ByteBuffer?byteBuffer?=?ByteBuffer.allocate(1024); ????????????????socketChannel.read(byteBuffer); ????????????????byteBuffer.flip(); ????????????????System.out.println(new?String(byteBuffer.array())?+?":::::::::::::::::::"); ????????????????byteBuffer.clear(); ????????????} ????????????iterator.remove(); ????????????System.out.println(selectionKeySet.size()); ????????} ????} }在client結束后,我末尾打印的selectionKeySet.size()方法,本來是0,結果循環一遍siez卻變成1了,仍然會不停的進入selectionKey.isReadable()方法,導致死循環最后iterator應該是移除掉了,但集合里面總有一個SelectionKeyImp的對象,這個是哪里來的?我末尾打印的selectionKeySet.size()方法,本來是0,結果循環一遍又這是控制臺:1 [sun.nio.ch.SelectionKeyImpl@4b9e13df] accept===== 0 1 [sun.nio.ch.SelectionKeyImpl@2b98378d] read===== 你好好好好?? 0 1 [sun.nio.ch.SelectionKeyImpl@2b98378d] read=====??????? ???? 0 1 [sun.nio.ch.SelectionKeyImpl@2b98378d] read=====??????? ? 0 1 [sun.nio.ch.SelectionKeyImpl@2b98378d] read=====????? 0 1 [sun.nio.ch.SelectionKeyImpl@2b98378d] read=====
查看完整描述

1 回答

  • 1 回答
  • 0 關注
  • 3023 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號