songyy
songyy

Reputation: 4563

Java nio OP_READ not executed when OP_WRITE exists, in Android?

I'm trying to write a Server in Android, using NIO. I've registered both OP_READ, OP_WRITE after my ServerChannel got accepted.

However, the wired thing is... in the while loop, after I do:

SelectionKey key = (SelectionKey) iterator.next();
iterator.remove();

in the:

if(key.isReadable()){
} else if(key.isWritable()){

It seems that the isReadable never returned true.

My client code is two threads, one thread for reading and another thread for writing. I wonder why is that so..? I think it would be helpful if anyone can give me some reference to the handling of client side in Java NIO.

Thanks a lot,

Upvotes: 0

Views: 955

Answers (2)

songyy
songyy

Reputation: 4563

I made a mistake understanding the .register method, the correct way:

client.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);

while what I did was:

client.register(selector, SelectionKey.OP_READ);
client.register(selector, SelectionKey.OP_WRITE);

Thus the later replaced the former.

Upvotes: 0

user207421
user207421

Reputation: 310884

You shouldn't normally register OP_WRITE. It is almost always ready. You should only use it when you get a short write result, which indicates that the send buffer is full. OP_READ on the other hand is only ready when there is data in the send buffer. There's nothing in your answer to suggest that there was, at the instant in question. I'm wondering whether you don't have these states back to front mentally somehow.

Upvotes: 3

Related Questions