Selector on Android sockets behaves strangely?

This code has major problems on any platform.

The following code works on Java This code has major problems on any platform. You aren't clearing the selectedKeySet. Normally this is done by iterating over it and calling Iterator.remove(), but in this case you should call selectedKeys().clear() as you aren't doing that, although you really should be: see below.

You shouldn't register with interestOps=validOps(). You should register OP_CONNECT until finishConnect() returns true, and thereafter either OP_READ or OP_WRITE, depending on what you want to do next. If the connection doesn't succeed, finishConnect() throws an IOException, on which you should close the channel.

You aren't doing that. If the connection hasn't finished yet, finishConnect() returns false, in which case you should just keep selecting. It doesn't make any sense to cancel the key at that point.

If selres > 1 you aren't processing any selected keys at all. The test should be if (selRes > 0), and it isn't really necessary, as iterating over the selectedKeySet will just iterate zero times; however selRes == 0 does indicate that select() timed out, which can be useful if you want to consider timeouts.

Thank you very much for your comments. Since the code is not mine, and selectors are designed in some perverted way, it's not easy to understand the code. However, all your remarks are applicable to code which is never executed simply because selRes == 0 immediately.

Even if I replace timeout with 0 (which supposedly means "wait infinitely", the code returns immediately. And yes, I tried using OP_CONNECT instead of validOps() - didn't help. Also, this code has been working for years on desktop.

– Eugene Mayevski 'EldoS Corp Sep 17 at 7:51 I've posted solution in my own answer. – Eugene Mayevski 'EldoS Corp Sep 17 at 8:35.

The problem has a weird solution found in seemingly unrelated bug-report in Android bug tracker. Android Emulator doesn't support IPv6 and while I don't pretend to request IPv6, it seems that by default Selector attempts to work on IPv6 stack. Once the following lines are added, my code starts to work correctly: java.lang.System.

SetProperty("java.net. PreferIPv4Stack", "true"); java.lang.System. SetProperty("java.net.

PreferIPv6Addresses", "false").

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions