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)
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)