Difference between select() and selectNow()
Hi would like to know more about the difference between Selector.select() and Selector.selectNow()
Background: I wrote a HTTP chat server and have problems to receive a full POST request (only with Firefox, IE is working), if i use Selector.select(). The last two line, including query string, are missing.
If i use Selector.selectNow() all works fine, but the CPU load is at 100%, so i need a Thread.sleep() in the for-loop to avoid this.
Here my code:
publicvoid listen()
{
SelectionKey key =null;
try{
for (;;)
{
readSelector.select();
//readSelector.selectNow(); <==== here the selectNow()
Iterator it = readSelector.selectedKeys().iterator();
while (it.hasNext()){
key = (SelectionKey) it.next();
if (key.isValid())
{
if ((key.readyOps() & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT)
{
SocketChannel clientChannel;
clientChannel = sSockChan.accept();
clientChannel.configureBlocking(false);
SelectionKey readKey = clientChannel.register(readSelector, SelectionKey.OP_READ);
readKey.attach(new Connection(server, readKey));
}
else
if ((key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ)
{
Connection c = (Connection)key.attachment();
c.read();
}
}
else
{
key.cancel();
//readSelector.wakeup();
}
it.remove();
}
}
/*try
{
Thread.sleep(10);
}
catch (InterruptedException ie) {}
*/
}catch (IOException e){
key.cancel();
}catch (NullPointerException e){
// NullPointer at sun.nio.ch.WindowsSelectorImpl, Bug: 4729342
}
}
And here the codefor read():
publicvoid read()
{
try
{
readBuffer.clear();
// read from the channel into our buffer
int nbytes = 1;
while (nbytes > 0)
{
nbytes = channel.read(readBuffer);
if (nbytes == -1)
logout();
else
{
readBuffer.flip( );
String str = asciiDecoder.decode(readBuffer).toString();
readBuffer.clear();
sb.append( str );
}
}
}
catch (IOException io){}
catch (Exception e){}
}
Any hints or ideas?
Thanks
TheChief

