Java DatagramSocket (UDP Socket) only receives when previously sent packet

I have the following problem:

I have an extremely simple Java Datagram client and server located on a remote machine. And the client will not receive anything from the server if he has not previously sent the packet to the server (no matter what information was stored in the packet)

This is what my client looks like:

    public static void TheClient() throws Exception { 
        ds = new DatagramSocket(clientPort); 
        while(true) { 
            DatagramPacket p = new DatagramPacket(buffer, buffer.length);   
            ds.receive(p); 
            System.out.println(new String(p.getData(), 0, p.getLength())); 
        } 
    } 

      

Basically all it does is listen on the clientPort and then print whatever it receives. However, this will not work.

Now its small modification solves the problem:

public static void TheClient() throws Exception {
    ds = new DatagramSocket(clientPort); 

    //Sending an empty packet
    byte tempBuffer1[] = new byte[10];
    InetAddress address = InetAddress.getByName(SERVER_IP);
    DatagramPacket packet1 = new DatagramPacket(
            tempBuffer1, tempBuffer1.length, address, serverPort);
    ds.send(packet1);

    while(true) { 
        DatagramPacket p = new DatagramPacket(buffer, 
                buffer.length);     
        ds.receive(p); 
        System.out.println(new String(p.getData(), 0, 
                p.getLength())); 
    } 
} 

      

Does anyone know what might be causing this problem? While the workaround did solve the problem, it doesn't make any sense to me why this won't work initially, so the solution may not work on all computers.

Also, it should be noted that the code works fine when both client and server are on the same machine.

+3


source to share


2 answers


Check if your PC is using a private IP address, usually one of which starts with "10.xxx" or "192.168.xx". If so, the most likely reason is using a NAT-based firewall that uses one public address and multiple private addresses.



When you send an outgoing packet, the firewall knows which internal address the returned packet should receive. However, when a connection is initiated from an external address, it has no way of knowing which internal address should receive traffic. Most SOHO (small office / home office) routers will allow you to "redirect" traffic to a specific internal IP address. If you are using DHCP, you need to assign yourself a static IP address, or your port forwarding may stop working in the future because it grabs a different IP address.

+1


source


This happens when AWS EC2

. Client side port not opening on your firewall (security group). When your client sends a packet to the server, the firewall allows you to receive data from the server for a short time. The client can receive from the server without sending anything to the server if the client port on the firewall is open.



0


source







All Articles