Re: non blocking sockets and alternatives
conrad wrote:
It seems either non-blocking sockets can be used or
blocking sockets with two threads, one for reading and
the other for writing. Is this correct?
Or blocking sockets with +one+ thread if your conversations are
transactional. Most people do this.
My next question is this, I was messing about with
Java's non blocking sockets and registered the
read and write operations with the socket channel.
That's your first mistake. You should only register OP_WRITE when you
have something to write, and deregister it immediately the data is
completely written. Otherwise the selector loop spins, because OP_WRITE
is always ready unless the socket send buffer is full, which is usually
a transient condition.
out.write(buffer);
Never ignore the result of a non-blocking write. This loop should be
written as follows:
int readCount, writeCount;
while ((readCount = in.read(buffer)) > 0)
{
try
{
buffer.flip();
writeCount = out.write(buffer);
if (writeCount == 0)
{
out.register(selector, SelectionKey,OP_WRITE);
break;
}
}
finally
{
buffer.compact();
}
}
if (readCount < 0)
in.close();
ByteBuffer buffer = ByteBuffer.wrap("myusername\r\n".getBytes());
buffer.flip();
I don't think you have to flip after a wrap, but I could be wrong.
it seems Java structures the stream
between client and server by doing the following:
size_of_data + the_data
Nope. It just sends the data you sent. Sometimes *applications* prepend
a size word to a transaction, so you know when you've read it all.
I clearly need
a Java book on non-blocking input/output
<shameless plug>
http://www.telekinesis.com.au/wipv3_6/FundamentalNetworkingInJava.A21
</shameless plug>