Search code examples
javaudppacketpacket-loss

Java UDP packet sending and receiving issue


I'm working on a project for class using Java and UDP senders and receivers. The premise of the problem is to read in a text file, store the contents within a packet, send the packet, receive the packet, and read out the file on screen and create a new text document on the receiving computer of an identical text file.

I have all of that working. When I test with a local host it appears to work 100% of the time. When I send it from my laptop to my PC it appears to work 100% of the time. However, when I send it from my PC to my laptop it does not work.

I have several System.out debug statements to verify some of the information I send. I know that the text file should take 7 packets. However, whenever I send it from my PC to my laptop it says that I am sending 46 packets.

My initial thought is that maybe the packets are being sent out of order. The first packet I am sending indicates how many packets the receiver should be expecting to receive. I thought maybe for some reason the "46" could indicate a capital "F" so I removed all the capital "F" and it still says I'm sending 46 packets.

I thought maybe I was sending too much information at once so I used Thread.sleep() to give my receiver time to keep up -- that did not work either.

Finally, I read through the Oracle Documentation and some posts online and found out that UDP is unreliable. So, I'm assuming it could potentially be that. However, I want to just verify that that could be the issue.

Or if anyone has a better idea as to what could be causing the problem that would be awesome as well!

Thanks for your help :)


Solution

  • Yes, UDP is an unreliable protocol. UDP messages may be lost, and neither the sender or receiver will get any notification.

    The 7 packets becomes 46 packets is typically due to fragmentation at the IP packet level. The protocol level beneath IP (e.g. physical ethernet packets, wifi packets etc) typically has a hard limit on the largest IP packet that can be sent "in one go", and similar limits are imposed by network routers, gateways and so on. If an IP packet that is larger than the limit is sent, two things can happen:

    • The IP packet may turned into "fragments" that need to be reassembled by the receiver.

    • The intermediate equipment can sent an ICMP message back to the sender telling it to send smaller IP packets.

    In either case, the net result is that the number of IP packets needed to send a given sized UDP message can vary, depending on the network.

    Of course, if a UDP message needs to be sent as multiple IP packets, AND there is local congestion in the network, that will increase the likelihood of packets, and hence messages failing.


    But the bottom line is that UDP is not reliable. If you want reliability, the simple solution is to use TCP instead.