setSoTimeout的Javadoc说:
将此选项设置为非零超时后,对此DatagramSocket的receive()的调用将仅在此时间量内阻塞。如果超时到期,则将引发java.net.SocketTimeoutException,尽管DatagramSocket仍然有效。
因此,如果要在1秒后未收到任何响应的情况下发送数据包,则只需使用
socket.setSoTimeout(1000L);boolean continueSending = true;int counter = 0;while (continueSending && counter < 10) { // send to server omitted counter++; try { socket.receive(packet); continueSending = false; // a packet has been received : stop sending } catch (SocketTimeoutException e) { // no response received after 1 second. continue sending }}


