Simple UDP communication example


SDK Version: 
M3

Today I’m going to show you how to create a really easy and simple UDP message sender and receiver.


Udp communication time diagram.

The User Datagram Protocol (UDP) is one of the core members of the Internet Protocol Suite, the set of network protocols used for the Internet. With UDP, computer applications can send messages, in this case referred to as datagrams, to other hosts on an Internet Protocol (IP) network without requiring prior communications to set up special transmission channels or data paths. /wiki/

First of all let’s see the server side:

  1. String messageStr="Hello Android!";
  2. int server_port = 12345;
  3. InetAddress local = InetAddress.getByName("192.168.1.102");
  4. int msg_length=messageStr.length();
  5. byte[] message = messageStr.getBytes();
  6. DatagramPacket p = new DatagramPacket(message, msg_length,local,server_port);
  7. s.send(p);

This code snippet is easy to understand from variable names.

Now see client side:

  1. String text;
  2. int server_port = 12345;
  3. byte[] message = new byte[1500];
  4. DatagramPacket p = new DatagramPacket(message, message.length);
  5. DatagramSocket s = new DatagramSocket(server_port);
  6. s.receive(p);
  7. text = new String(message, 0, p.getLength());
  8. Log.d("Udp tutorial","message:" + text);
  9. s.close();

You must to set the incoming message's maximum size.

  1. byte[] message = new byte[1500];

That's it. And of course it works fine on Android too. :)