setSotimeout on a datagram socket

江枫思渺然 提交于 2019-12-02 01:20:40

The javadoc for setSoTimeout says:

With this option set to a non-zero timeout, a call to receive() for this DatagramSocket will block for only this amount of time. If the timeout expires, a java.net.SocketTimeoutException is raised, though the DatagramSocket is still valid.

So, if you want to send packets if no response has been received after 1 second, you just have to use

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
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!