UDP Programming with Java

02 Mar 2011 by

Resource on UDP Programming is limited and even rare for some programming languages. For TCP Programming, I guess, there is a lot and many languages support it. For example, Java, C, C++, C#, WinSock, etc. So this article is to contribute to those limitation by taking an advantage of java.net package that supports UDP programming interface. The understanding of UDP and TCP is required.

UDP uses Datagram as the main packet to be wrapped before sending to destination. What is Datagram anyway?

Datagram is an independent, self-contained message sent over the Internet whose arrival, arrival time and content are not guarantee.

The datagram packet flow is as follow:

UDP Datagram

Note: While preparing the data, we just need DATA, Destination IP, and Destination Port. But while sending, datagram will automatically be inserted Source IP, and random Source Port.

Sender: UDP Socket programming

1. Create UDP Socket for sending datagram

DatagramSocket socket = new DatagramSocket();

2. Prepare datagram for sending

byte[] data = new byte[256];
InetAddress address = InetAddress.getByName("192.168.1.8");
DatagramPacket pack = null;
pack = new DatagramPacket(data, data.length, address, 8888);

3. Send

socket.send(pack);

4. Receive

Prepare new datagram first for holding the incoming packet. The array of byte must be clear in advance.

socket.receive(pack);

Receiver: UDP Socket programming

1. Start listening for datagram on a certain socket

DatagramSocket socket = new DatagramSocket(Server_Port);

2. Prepare datagram for receiving

byte[] data = new byte[256];
DatagramPacket pack = new DatagramPacket(data, data.length);

3. Start listening for a datagram

socket.receive(pack);

4. Obtaining the data and address and port of sender

int port = pack.getPort();
InetAddress address = pack.getAddress();
String content = new String(pack.getData, 0, pack.getLength());

Example

In this example, we shows a simple scenario to send “Hello” message from a client to server. Upon receiving, server will reverse the string. For instance, “Hello” to be “olleH”. The reversed string is sent back to client. Hence, this example is a complete of sending and receiving at both client and server.
SimpleUDPServer.java

import java.io.IOException;
import java.net.*;

/**
 * @author lycog
 */
public class SimpleUDPServer {
  public static void main(String[] args){
    DatagramSocket socket = null;
    DatagramPacket inPacket = null; //recieving packet
    DatagramPacket outPacket = null; //sending packet
    byte[] inBuf, outBuf;
    String msg;
    final int PORT = 8888;

    try{
      socket = new DatagramSocket(PORT);
      while(true){
        System.out.println("Waiting for client...");

        //Receiving datagram from client
        inBuf = new byte[256];
        inPacket = new DatagramPacket(inBuf, inBuf.length);
        socket.receive(inPacket);

        //Extract data, ip and port
        int source_port = inPacket.getPort();
        InetAddress source_address = inPacket.getAddress();
        msg = new String(inPacket.getData(), 0, inPacket.getLength());
        System.out.println("Client " + source_address + ":" + msg);

        //Send back to client as an echo
        msg = reverseString(msg.trim());
        outBuf = msg.getBytes();
        outPacket = new DatagramPacket(outBuf, 0, outBuf.length,
                             source_address, source_port);
        socket.send(outPacket);
      }
    }catch(IOException ioe){
      ioe.printStackTrace();
    }
  }

  private static String reverseString(String input) {
    StringBuilder buf = new StringBuilder(input);
    return buf.reverse().toString();
  }
}

SimpleUDPClient.java

import java.io.IOException;
import java.net.*;

/**
 * @author lycog
 */
public class SimpleUDPClient {
  public static void main(String[] args){
    DatagramSocket socket = null;
    DatagramPacket inPacket = null;
    DatagramPacket outPacket = null;
    byte[] inBuf, outBuf;
    final int PORT = 8888;
    String msg = null;

    try {
      InetAddress address = InetAddress.getByName("127.0.0.1");
      socket = new DatagramSocket();

      //Convert string to byte and send to server
      msg = "Hello";
      outBuf = msg.getBytes();
      outPacket = new DatagramPacket(outBuf, 0, outBuf.length,
              address, PORT);
      socket.send(outPacket);

      //Receive reversed message from server
      inBuf = new byte[256];
      inPacket = new DatagramPacket(inBuf, inBuf.length);
      socket.receive(inPacket);

      String data = new String(inPacket.getData(), 0, inPacket.getLength());

      System.out.println("Server : " + data);

    } catch (IOException ioe) {
      System.out.println(ioe);
    }
  }
}

Please visit TCP Programming with Java for comparison. It was written for same objective.

6 responses so far

Leave a Reply