0

For a reliable connection you have to use TCP.

However, I would like to know if there is a way to modify my code so that I can check for lost packets in UDP

 try {
        DatagramSocket socket = new DatagramSocket(5000);

        while(true) {
            byte[] buffer = new byte[50];
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
            socket.receive(packet);
            System.out.println("Text received is: " + new String(buffer, 0, packet.getLength()));

            String returnString = "echo: " + new String(buffer, 0, packet.getLength());
            byte[] buffer2 = returnString.getBytes();
            InetAddress address = packet.getAddress();
            int port = packet.getPort();
            packet = new DatagramPacket(buffer2, buffer2.length, address, port);
            socket.send(packet);
        }

    } catch(SocketException e) {
        System.out.println("SocketException: " + e.getMessage());
    } catch(IOException e) {
        System.out.println("IOException: " + e.getMessage());
    }
}
Prog101
  • 109
  • 2
  • 10
  • 2
    Nope. The generally accepted method is to wait for an acknowledge from the receiver that the packet was received, and send the packet again after a time out if no acknowledge is received. But that's exactly what TCP does, so why re-invent the wheel? Just use TCP. – markspace Dec 03 '20 at 01:03
  • You need to implement an application-layer protocol to do that. You would have a specific datagram format with a header that uses something like sequence numbers to determine if datagrams are lost. That is how TCP and other reliable protocols do it. – Ron Maupin Dec 03 '20 at 01:03
  • I've closed this as a dup of a C# question ... because the answer is essentially the same for any programming language. – Stephen C Dec 03 '20 at 02:37

1 Answers1

1

Since the transport protocol does not provide facilities, the application protocol needs to do so.

You could for example make the sender add a sequence number into each message, and the receiver would then know that a datagram had been lost, or (also possible) duplicated.

That lets you detect loss, but does nothing to allow you to recover from it.

You'd need in the receiver to track expected sequence numbers per sender, of course.

user14644949
  • 321
  • 1
  • 3
  • 1
    I forgot to point out that you only know (for example) that message 17 was lost when the message you get after number 16 is numbered 18. This assumes there is supposed to be a "number 18" in a timely manner. If you can't do anything until number 17 was seen, then it gets more complicated. – user14644949 Dec 03 '20 at 01:13
  • Hie. I just started working on it now, but I seem to be having some problems. After the first missing packet, it starts adding other packets as missing. Here is my code: http://pastie.org/p/3nQDJVlmy2ZNMQ8fZt2NDN – Prog101 Dec 03 '20 at 18:54