Search code examples
javasocketsclient-serverdatagram

how much time java.net.DatagramSocket will wait for a client request if inactive for long time?


I am experiencing problems when using a UDP datagram packet, in the program I bind a UDP port and listen messages on it. This normally works fine, but if the port remains idle for a long time, the program automatically terminates the UDP socket. Unfortunately, the log file is huge and it is difficult to find the exception. Please help me find a way to keep the UDP port alive forever. Thanks in advance.

Here is my code:

socket = new DatagramSocket(port);
setBindSocket(true);            
socket.setSoTimeout(60000);

while(isBindSocket()) {
    try {               

        byte[] buffur = new byte[512];              
        DatagramPacket inputPacket = new DatagramPacket(buffur, buffur.length);
        inputPacket.setLength(buffur.length);
        socket.receive(inputPacket);
        byte [] bString = inputPacket.getData();
        String hString = new String(bString);        

    } catch (SocketTimeoutException ste) {
    } catch (Exception e) { 
        e.printStackTrace();
    }
}

Solution

  • The following statement changes the socket's behavior when receiving - if no datagram arrives in 60 seconds, a SocketTimeoutException is thrown.

    socket.setSoTimeout(60000);
    

    Maybe I have misunderstood your question.