免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1993 | 回复: 1
打印 上一主题 下一主题

关于非阻塞socket问题,急 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2007-01-08 10:18 |只看该作者 |倒序浏览
各位前辈,我用

  1. Selector selector = null;
  2.     try {
  3.         // Create the selector
  4.         selector = Selector.open();
  5.         SocketChannel sChannel1 = createSocketChannel("hostname.com", 80);
  6.         sChannel1.register(selector, sChannel1.validOps());
  7.     } catch (IOException e) {
  8.     }
  9.    
  10.     while (true) {
  11.         try {
  12.             selector.select(1000);
  13.         } catch (IOException e) {
  14.             break;
  15.         }
  16.    
  17.         Iterator it = selector.selectedKeys().iterator();
  18.         SelectionKey selKey = (SelectionKey)it.next();

  19.         it.remove();
  20.         processSelectionKey(selKey);
  21.       }
  22.    
  23.     public void processSelectionKey(SelectionKey selKey) throws IOException {
  24.         if (selKey.isValid() && selKey.isConnectable()) {
  25.             // Get channel with connection request
  26.             SocketChannel sChannel = (SocketChannel)selKey.channel();
  27.    
  28.             boolean success = sChannel.finishConnect();
  29.             if (!success) {
  30.                 selKey.cancel();
  31.             }
  32.         }

  33.         if (selKey.isValid() && selKey.isReadable()) {
  34.             SocketChannel sChannel = (SocketChannel)selKey.channel();
  35.         }
  36.          }
  37.     }

复制代码


这样select每秒都返回一次0,然后要等22秒才能返回一次1,才能到processSelectionKey函数实现socket连接?我早就在selector中注册了的,为啥每次都返回0 啊?。

什么情况下什么事件会让select返回1啊?

另外isConnectable什么时候会返回true?看文档说已经连接了就返回true,感觉不太是这样的、谢谢

[ 本帖最后由 HappyWin 于 2007-1-8 10:19 编辑 ]

论坛徽章:
0
2 [报告]
发表于 2007-01-08 23:28 |只看该作者
那肯定是selector注册的事件出现了
才返回1吧
看下java nio这本书清楚点
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP