0
votes

I cannot get a response when i use the Udp DatagramSocket and DatagramPacket classes. I tested the same server with Tcp Socket and it responds properly.

public static void main(String[] args) throws IOException {

    DatagramSocket socket = new DatagramSocket(0); // random available port
    System.out.println("port: " + socket.getLocalPort());
    socket.setSoTimeout(3000); // 3 seconds timeout

    DatagramPacket request = new DatagramPacket(new byte[1], 1, InetAddress.getByName("time.nist.gov"),
            13);

    DatagramPacket response=new DatagramPacket(new byte[1024],1024);

    socket.send(request);
    socket.receive(response);

    String daytime = new String(response.getData(), 0, response.getLength(),
            "US-ASCII");
    System.out.println(daytime);

}
1
UDP is not reliable. Packets may be lost. Did you make sure the other side receives your request? Firewall could be an issue. Also, you have to use another port. 123 I believe is for UDP.Fildor
For the reserved port have a look here: en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbersSebastian Walla

1 Answers

1
votes

This does not work, because TCP is peer to peer and requires someone to read on the other end.

UDP however is fire and forget, (point to multipoint) so the moment you .send(...) the packet is already under way. Your call to .receive(...) simply comes to late.

To fix your example spawn a thread that calls .receive(...) before calling .send(...) in the main thread.

Your code is also problematic for the same reasons with TCP. It simply works because your single byte sent fits easily into the buffers on the stack. So to break your example with TCP as well, simply make the payload you are sending large enough. If no one is receiving on the other end, your send operation will block indefinitely (or timeout).