简体   繁体   中英

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 ?

事实证明代码运行良好,3G服务提供商阻止了一些UDP数据包。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM