I am testing a UDP echo server, is the following code correct?
DatagramSocket s = ...
DatagramPacket p = new DatagramPacket(new byte[512], 512);
...
s.recieve(p);
s.send(p);
My question is, can I send the DatagramPacket
just as I recieved it? According to the java specification, the contructor I used constructs a DatagramPacket 'for recieving use'. I am not sure if that state changes when the packet has been modified through s.recieve
, or if that 'for recieve use state' is permanent.
If the code is correct, is there any reason why in the tutorial they construct a whole new DatagramPacket
? (maybe just clarity?)
https://docs.oracle.com/javase/tutorial/networking/datagrams/clientServer.html
Yes, and it's quite common. If you receive a request, the DatagramPacket already has the return address in it, so all you need to do is put the response data into it and send it back.