Android UDP Client and Server Communication Programming–Illustrated with Example

UDP and TCP are the two main transport protocols used in today’s Internet. This post illustrates how to program UDP client and server in Android.

Android UDP communication uses the APIs provided in java.net package, which are also available in Java standard edition etc.

To program a UDP server, one can use the code below,

private void runUdpServer() {

    String lText;

    byte[] lMsg = new byte[MAX_UDP_DATAGRAM_LEN];

    DatagramPacket dp = new DatagramPacket(lMsg, lMsg.length);

    DatagramSocket ds = null;

    try {

        ds = new DatagramSocket(UDP_SERVER_PORT);

        //disable timeout for testing

        //ds.setSoTimeout(100000);

        ds.receive(dp);

        lText = new String(lMsg, 0, dp.getLength());

        Log.i("UDP packet received", lText);

        textView.setText(lText);

    } catch (SocketException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    } finally {

        if (ds != null) {

            ds.close();

        }

    }

}

The code opens a DatagramSocket and calls the receive method. Note that if setSoTimeout() is not called, the receive method is a block call, which means the execution will block until a udp message is received. If you don’t want this behavior, set the timeout to a value you want and catch for timeout exception.

For the client side, it’s also simple,

private void runUdpClient()  {

    String udpMsg = "hello world from UDP client " + UDP_SERVER_PORT;

    DatagramSocket ds = null;

    try {

        ds = new DatagramSocket();

        InetAddress serverAddr = InetAddress.getByName("127.0.0.1");

        DatagramPacket dp;

        dp = new DatagramPacket(udpMsg.getBytes(), udpMsg.length(), serverAddr, UDP_SERVER_PORT);

        ds.send(dp);

    } catch (SocketException e) {

        e.printStackTrace();

    }catch (UnknownHostException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    } catch (Exception e) {

        e.printStackTrace();

    } finally {

        if (ds != null) {

            ds.close();

        }

    }

}

The code also opens a DatagramSocket, and create a DatagramPacket with destination address and port number. It calls send method to send the DatagramPacket out.

Note that to use the network socket (DatagramSocket, in our case), you’ll need to request for INTERNET permission. Adds the following line to AndroidManifest.xml will do,

<uses-permission android:name="android.permission.INTERNET"/>

Download and Screenshots

You can download the complete example here (client) and here (server) or from my github android tutorial repo here. If you run server and client on your android device (server first), you’ll get something like this,

Untitled

Figure 1. Screenshot for UDP Communication Client and Server

The UDP server receives the UDP datagram from UDP client and outputs the message to a TextView.

0 thoughts on “Android UDP Client and Server Communication Programming–Illustrated with Example”

  1. Eu estou a tentar fazer uma comunicação com o programa cliente e um progrma feito em pascal. Mas não esta a funcionar. Sabe me dar uma razão?
    Gostei bastante do poste, bom trabalho mesmo.

    1. –. dont work for me on android 2.1 and 2.2. access to socket denied; works only in java-application on pc. downloadable version cant be imported properly.

    1. No. It’s a simple UDP server, just for illustrating the Android API. Lots of work needs to be done in order to use it for your purpose.

      1. When I changed: Get serverAddr from a real ip address instead of “127.0.0.1”, it works.
        I got this real ip address after connecting 2 device by WiFi Direct.

        In device, it seems not have local address “127.0.0.1” like in PC

  2. Hi!
    This is really useful, but I can only receive the first message and it gets stuck in that…do you have any idea of how can i solve it? thank you very much!!!

  3. hi, i want send the imei, and other device data.

    i add this variable:
    final TelephonyManager imei = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);

    and dont works the client part.

    you know any solution?

Leave a Reply

Your email address will not be published. Required fields are marked *