Java API Tutorial - Java DatagramPacket.getData()








Syntax

DatagramPacket.getData() has the following syntax.

public byte[] getData()

Example

In the following code shows how to use DatagramPacket.getData() method.

//from   w  ww  .  j  a v  a  2 s.  c  o  m
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class Main {

  public static void main(String[] args) {
    try {
      byte[] buffer = new byte[1024];
      DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

      DatagramSocket socket = new DatagramSocket(5002);

      System.out.println("Waiting for a packet...");
      socket.receive(packet);

      System.out.println("Just received packet from " + packet.getSocketAddress());
      buffer = packet.getData();

      System.out.println(new String(buffer));

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

The code above generates the following result.