Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Selector returns set of keys which are already processed in loop before  RSS feed

 
Harshil Mehta
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi. i am facing problem as following:

i have a Selector and a ServerSocketChanner with non-blocking configuration.

now in main loop, i perform

while(true) {
int keysAdded = selector.select();
if(keysAdded == 0) {
continue;
}
Set keysReady = selector.selectedKeys();

Iterator itrKey = keysReady.iterator();
while(itrKey.hasNext()) {
selectedKey = (SelectionKey) itrKey.next();
itrKey.remove();
}
} //end while

Only single client is connecting to it and closes socket.

when the loop iterates, the selector always returns '1' even at first time, the key is processed and removed.

so how to deselect keys which were selected earlier?
 
David Harkness
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're not handling whatever operation is available on the keys, so the next time you do select(), that operation is ready again. Removing the key from the selected set doesn't clear it's ready state, IIRC.

If you get a connection request operation, you must accept or deny it. If you get an I/O ready state, you must read or write appropriately.

Basically, each time through the outermost while loop the Selector is saying, "Some client is waiting to connect." That you tell the Selector that you got the message (removed the key from the selected set) doesn't change the fact that the client is still waiting to connect.
 
Harshil Mehta
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi david,

thnx a lot. u r right. it solved my problem...
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!