Reputation: 2640
I have working code that uses non-blocking IO to fetch UDP packets like this:
DatagramChannel channel = DatagramChannel.open();
channel.socket().bind(new InetSocketAddress(AUDIO_PORT));
channel.configureBlocking(false);
while(true){
ByteBuffer packet = ByteBuffer.allocate(MAX_PACKET);
if(channel.receive(packet) != null){
//Got something!
...
}
...
}
That works perfectly. Now I'm trying to do exactly the same, only this time I want to use selectors, like this:
//Create a datagram channel, bind it to port, configure non-blocking:
DatagramChannel channel = DatagramChannel.open();
channel.socket().bind(new InetSocketAddress(AUDIO_PORT));
channel.configureBlocking(false);
//Create a selector and register it:
Selector selector = Selector.open();
channel.register(selector, SelectionKey.OP_READ);
//Spin
while(true){
//If there's a packet available, fetch it:
if(selector.selectNow() >= 1){
//**CODE NEVER REACHES THIS POINT**
ByteBuffer packet = ByteBuffer.allocate(MAX_PACKET);
channel.receive(packet);
...
}
...
}
Due to the application I'm making, I really need it to be non-blocking IO (even though it looks like I'm just spinning in my example), and blocking with a short timeout just won't work. I also really have to use Selectors. Issue is, even though I have a server actively sending packets to the device's AUDIO_PORT port, the select() operation always returns 0. I know the server app is doing its work since the first snippet works fine. Am I setting up the Selector wrong? I'm guessing I'm missing some step, but I just can't figure it out.
Upvotes: 3
Views: 7338
Reputation: 310893
As I believe we have discussed previously in other threads, if the first code works and the second doesn't, Selectors must be broken in Android. Your code is correct (as long as you clear the selected key set of the Selector every time you get a non-zero return). You can verify that by running it on a Java platform.
You might consider changing select() == 1
to select() > 0
for greater generality, and then looping around the selected-key set as you will see in all the examples, but it shouldn't affect the correctness of this code.
As I also believe we have discussed, you could try blocking mode with a short read timeout instead of the Selector.
NB You aren't spinning, you are blocking forever in select().
Upvotes: 1