Adding timeout to DatagramSocket - receive()

后端 未结 2 1189
死守一世寂寞
死守一世寂寞 2020-12-31 01:41

I need to create a 10 second timeout on this part of the code

DatagramPacket getack = new DatagramPacket(incoming, incoming.length);
socket.rece

2条回答
  •  情深已故
    2020-12-31 01:50

    That should work for your example.

    socket.setSoTimeout(10000);
    while(true) {
        DatagramPacket getack = new DatagramPacket(incoming, incoming.length);
        try {
            socket.receive(getack);
        } catch (SocketTimeoutException e) {
           // resend
           socket.send(data);
           continue;
        }
        // check received data...
    }
    

提交回复
热议问题