Bad NIO socket performance

I

iksrazal

I'm having problems tuning a read operation. This method actually is
invoked by a client call, so it doesn't register OP_ACCEPT or anything
like that.

The problem is that this method's completion time is equivalent to the
Selector.select(milliseconds) time. If its 5000, it completes in 5
seconds. 1000 results in one second. I'd really like it do the read
and break out of the loop when its ready, somehow.

private String readFromChannel (SocketChannel
sChannel) throws IOException
{
CharsetDecoder decoder =
this.ascii.newDecoder();
ByteBuffer buffer = ByteBuffer.allocate(2048);
CharBuffer charBuffer =
CharBuffer.allocate(2048);
StringBuffer dataRead = new StringBuffer();
Selector selector = Selector.open();
boolean hasRead = false;
// Register read activity on socket
sChannel.register(selector,
SelectionKey.OP_READ);
// Read response with 1000 mililiseconds timeout
while (selector.select(1000) > 0)
{
System.out.println("selector looping...");
// Get set of ready objects
Set readyKeys = selector.selectedKeys();
Iterator readyItor = readyKeys.iterator();
// Walk through set
while (readyItor.hasNext())
{
System.out.println("iterator looping...");
// Get key from set
SelectionKey key =
(SelectionKey)readyItor.next();
// Remove current entry
readyItor.remove();
// Get channel
SocketChannel keyChannel =
(SocketChannel)key.channel();
if (key.isReadable())
{
// Read what's ready in response
while (keyChannel.read(buffer) > 0)
{
// Make buffer readable
buffer.flip();
// Decode buffer
decoder.decode(buffer, charBuffer,
false);
// Build string recieved
charBuffer.flip();
dataRead.append(charBuffer);
// Clear for next pass
buffer.clear();
charBuffer.clear();
// Indicate successful operation
System.out.println("length of data read:
" + dataRead.toString().length());
hasRead = true;
}
}//end key.readyOps()
}//end while iterator
}//end while selector

if (false == hasRead)
{
throw new IllegalStateException ("Socket read
operation timed out");
}

return dataRead.toString();
}

Any ideas?
iksrazal
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,965
Messages
2,570,148
Members
46,710
Latest member
FredricRen

Latest Threads

Top