nio read timeout ?

D

dchev

From the nio API docs, it appears to me that I should be able to set a
socket read timeout, but in practice, the read blocks without timing
out.
The old java.net APIs seem to work just fine.

I understand that I could use non-blocking mode and a Selector, but
that seemed overkill for my one little datagram exchange which runs in
its own thread.

Can anyone tell me why the following nio-based code does not timeout?
ie. Why does DatagramChannel object's socket().setSoTimeout(x) not
work?

Thanks!
-Dave

NIO-based snippet:
DatagramChannel channel = DatagramChannel.open();
ByteBuffer bbuf;
InetSocketAddress sa;
// skipping the part where sa and bbuf are initialized & prepared

channel.send(buffer, sa); // send a request
bbuf.clear();
channel.socket().setSoTimeout(1000); // set timeout to one second

sa = (InetSocketAddress) channel.receive(bbuf); // does NOT timeout


The following plain old java.net based code works fine
(so, yes, that's what I'm using. But I want to understand why the nio
code did not work)

DatagramSocket socket = new DatagramSocket();
// init/prepare byte[] cmd and InetSocketAddress sa
socket.send( new DatagramPacket(cmd, cmd.length, sa));
byte[] buffer = new byte[MAX_RX_SIZE];
DatagramPacket rxPkt = new DatagramPacket(buffer, buffer.length);
socket.setSoTimeout(1000);
socket.receive(rxPkt); // times out in one second as expected (if no
data)
 
D

dchev

hehe... well, I did find a better answer to this problem eventually (
Selector) but it was pretty funny to me for this reason:

1) my background was sockets interface with C, where I was accustomed
to using select() to receive responses.

2) learning java circa 1.1/1.2, it was a frustrating realization that
there was no select() and that I should put all receive handling in
separate threads (grrr)

3) circa 1.4, trying to move over to the nio channels (so that my
server socket accept() thread could be interrupted - grrr), I tried to
use the same model as in point 2, only to find that doesn't work and
the model in point 1 does again....

full circle for me!

someone could have at least told me to rtfm ;-)
I spent the last two months thinking very negatively of nio.
cheers,
-Dave
 

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

Members online

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,186
Members
46,740
Latest member
JudsonFrie

Latest Threads

Top