Posts

Showing posts from February, 2025

DatagramPacket setLength() tricky business

Image
Java Network Programming uses the DatagramPacket class as the data representation for UDP datagrams. Whether you want to send or receive it, it will be a DatagramPacket . In a recent exam, we asked our students to create a simple UDP echo server.   The logic of such a server is that it waits endlessly until it receives a UDP datagram and then sends it back to the same address (IP and port number) from which it came. Nothing complicated, but the devil is in the details, and some students wrote a program that would create a new DatagramPacket for each datagram received. It is not wrong, as it works, but it is a bit wasteful, as it places more stress on memory allocation and garbage collection than needed.  However, I was surprised when chatGPT commented on the code I got from DeepSeek-R1 as a sample solution, where a call to setLength() was made after each iteration. It did not make sense to me, but chatGPT went on for quite a while, reasoning why it was needed. Eventually...