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.

 

13 comments on “Android UDP Client and Server Communication Programming–Illustrated with Example

  1. dickie on said:

    This program crashes every time I try to load it

  2. dickie on said:

    Do you have any solution to this crashing everytime?

  3. Anonymous on said:

    Works with SGSII (2.3.4) and TF201 (4.0.3)

  4. Jorge on said:

    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.

    • hardy on said:

      –. 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.

  5. hi,
    does this UDP server can uni cast live video to web browser from android camera. thanks in advance

  6. michael on said:

    Works like a charm after editing it a bit.
    Thank you

  7. CLockwork on said:

    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!!!

  8. 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.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Set your Twitter account name in your settings to use the TwitterBar Section.