How to achieve a timeout when locking a DatagramChannel without using selectors

I get the feeling that I'm missing something really obvious here.

The general structure of my system makes me want to use a blocking DatagramChannel without Selectors to make everything simple. I am trying to do timeout processing by setting a timeout on a socket, but this does not seem to have an effect.

This pseudo-stated code gives a hint about what I'm trying to achieve.

  DatagramChannel channel = DatagramChannel.open ();
 channel.socket (). bind (some address);
 channel.socket (). setSoTimeout (3000);
 channel.send (outBuffer, peerAddress);

 channel.receive (inBuffer);

On the other hand, I have a UDP server that gives five quick answers, and then, for testing, it delays for about five seconds before delivering the sixth answer.

The delay does not raise a SocketTimeoutException. Why is this? The timeout set on the socket does not seem to be taken into account when calling channel.receive.

Regards, Fredrick

+4
source share
2 answers

Apparently, the timeout failure problem is not a bug with the DatagramChannel, but it is:

Not a mistake. SocketChannel (and DatagramChannel) read methods do not use support timeouts. If you need a timeout function, use the methods of the associated Socket object (or DatagramSocket).

Link.

+2
source

This is what I did:

Create an Interrupter Class

 static private class Interrupter implements Runnable { private final Thread th1; private volatile int wait=-1; private Interrupter(Thread ith1) { th1=ith1; } public void run() { while(true) { try{ if( wait<0 ){ th1.join(); break; } else{ Thread.sleep(wait); th1.interrupt(); wait=-1; } } catch(Exception e){} } } } 

Install Interrupter

 Interrupter ir1=new Interrupter(Thread.currentThread()); Thread th1=new Thread(ir1); th1.start(); // We need this so that later the wait variable // can be passed in successfully while( th1.getState()!=Thread.State.WAITING ); 

Use Interrupter

 try{ ir1.wait=waitTimeout; th1.interrupt(); // Receive on the socket dc2.receive(bb2); } catch(ClosedByInterruptException e){ // (Timed out) Thread.interrupted(); dc2.close(); // Handle timeout here // ... // We need this so that later the wait variable // can be passed in successfully while( th1.getState()!=Thread.State.WAITING ); } // Received packet ir1.wait=-1; th1.interrupt(); // We need this so that later the wait variable // can be passed in successfully while( th1.getState()!=Thread.State.WAITING ); Thread.interrupted(); 
0
source

All Articles