Search code examples
androidudpnatandroid-networking

Receive UDP packets on Android


I try to send and receive UDP packets continuously between an Android app and a server.

Is there any way to make that happen ?

My current networking code (running in a Thread) is shown bellow. The client is connected through 3G. The port configured client side is 1088.

The server just echo the packet to the client when received. The server receive the packet correctly from the client but the client doesn't receive anything back.

InetAddress serverAddr = InetAddress.getByName(SERVERIP);

Log.d(TAG, "S: Connecting...");
DatagramSocket socket = new DatagramSocket();
DatagramSocket receive_socket = new DatagramSocket(SERVERPORT, InetAddress.getByName("0.0.0.0"));

while(running) {
    DatagramPacket packet_send = new DatagramPacket(msg, msg.length, serverAddr, SERVERPORT);
    Log.d(TAG, "C: Sending: '" + new String(msg) + "'");
    socket.send(packet_send);

    // Prepare a UDP-Packet that can contain the data we want to receive
    DatagramPacket packet = new DatagramPacket(buf, buf.length);
    Log.d(TAG, "S: Receiving...");

    // Receive the UDP-Packet
    receive_socket.receive(packet);
    Log.d(TAG, "S: Received: '" + new String(packet.getData()) + "'");
    synchronized (this) {
        wait(500);
    }
}

I suspect the 3G connection is NATed (the server reports a port different from 1088). If so, is there anything I can do to overcome that ? Or is there anything wrong I do in my code ?


Solution

  • Turned out the code was working fine, the 3G service provider was blocking some UDP packets.