setSotimeout on a datagram socket

后端 未结 1 1751
情歌与酒
情歌与酒 2021-01-21 21:30

The server acts like an echo server. The clients sends 10 packets to server (1 sec of gap)

When Client receives packets from the server, sometimes the packets are lost.

相关标签:
1条回答
  • 2021-01-21 21:52

    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
        }
    }
    
    0 讨论(0)
提交回复
热议问题