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

[4192 byte] By [TheChiefa] at [2007-10-3 3:32:38]
# 1

Well I assume you know that select() waits indefinitely for something to happen and selectNow() doesn't wait at all.

The real issue is that you can't just assume you have a full message ready to be decoded, you have to keep reading until you know there's something complete there. In the case of HTTP you have to know there is a \r\n present so you can handle at least one header. This means that you just have to keep reading until you get something you can process.

ejpa at 2007-7-14 21:26:55 > top of Java-index,Archived Forums,Socket Programming...
# 2
Yes, i realized later, that the select waits and selectNow() not.Can you give me a little example how to read the HTTP request fully?
TheChiefa at 2007-7-14 21:26:55 > top of Java-index,Archived Forums,Socket Programming...