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