Java NIO 的调用 SelectionKey.OP_WRITE 不触发 isWritable()的疑惑??

2022-08-27 17:24:39 +08:00
 atfeel
这个代码我是不是写错了?执行 SelectionKey.OP_WRITE 不是应该触发 key.isWritable()的吗?


Selector selector = Selector.open();
DatagramChannel channel = DatagramChannel.open();
channel.configureBlocking(false);
channel.connect(new InetSocketAddress(Net.toInetAddress("139.155.182.112"), 3478));

SelectionKey selectionKey = channel.register(selector, 0);

findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
selectionKey.interestOps(SelectionKey.OP_WRITE);//这里是点击按钮,执行写人就绪
}
});


while (selector.select() > 0) {
Set<SelectionKey> keys = selector.selectedKeys();
// 遍历每个有可用 IO 操作 Channel 对应的 SelectionKey
for (SelectionKey key : keys) {
if (key.isWritable()) {//////////////////////这里为什么没有触发呢?????????????????????
Main.WriteLine("send...");
channel.write(ByteBuffer.allocate(1));
selectionKey.interestOps(0);
}
}
keys.clear();
}
1597 次点击
所在节点    Java
11 条回复
atfeel
2022-08-27 17:40:40 +08:00
要哭了,怎么都想不明白,又查不到想要的资料。。。
1461665214
2022-08-27 17:55:25 +08:00
你好像把 client 端和 server 端实现方式搞混了
atfeel
2022-08-27 18:15:46 +08:00
@1461665214 我看不出问题在哪里。。。
atfeel
2022-08-27 19:15:21 +08:00
有哪为 V 友知道的吗,急死我了!!!
cronglong
2022-08-27 21:35:38 +08:00
139.155.182.112 这个机器要 response to 你执行这个代码的机器时,才会触发吧
atfeel
2022-08-27 21:39:48 +08:00
@cronglong 不是吧,我还没发任何东西,DNS 服务器怎么可能会主动 response ??我这个是个 DNS 的功能,就是单方面的发送 DNS 查询,等待返回。。
tairan2006
2022-08-27 22:48:52 +08:00
你这是安卓吧?
dreamlike
2022-08-28 00:24:50 +08:00
selectionKey.interestOps(SelectionKey.OP_WRITE) 这个等价于 channel.register(selector, SelectionKey.OP_WRITE)
只是声明你需要监听什么事件 并不是触发可写的事件
默认情况下应该是直接 select 出来的就是可写的
atfeel
2022-08-28 09:57:02 +08:00
@tairan2006 这段代码,android 和 java 都是一样的结果。。
atfeel
2022-08-28 09:57:50 +08:00
@dreamlike 我看人家的开源项目也是这样用的,,不懂问题出在哪里
1461665214
2022-08-28 21:52:15 +08:00
@atfeel 为啥你 onClick 方法里不用 channel.write 直接写 而在事件循环里去写,我没在客户端代码里这么玩过

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/875838

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX