Java.net.DatagramPacket.getData() Method



Description

The java.net.DatagramPacket.getData() returns the data buffer. The data received or the data to be sent starts from the offset in the buffer, and runs for length long.

Declaration

Following is the declaration for java.net.DatagramPacket.getData() method

public byte[] getData()

Parameters

  • NA

Return Value

This method returns the buffer used to receive or send data.

Exception

  • NA

Example

The following example shows the usage of net.DatagramPacket.getData() method

package com.tutorialspoint;

import java.net.*;

class DatagramPacketDemo {

   public static void main(String args[]) throws Exception {

      // create a DatagramSocket object binded to port 9999
      DatagramSocket ds = new DatagramSocket(9999);

      // create a byte array buf
      byte buf[] = new byte[100];

      // create a DatagramPacket object
      DatagramPacket dp = new DatagramPacket(buf, buf.length);

      // recieve the datagram packet into dp
      ds.receive(dp);

      // data recieved in buf byte array
      buf = dp.getData();

      // convert byte array to string
      String data = new String( buf );

      // print data
      System.out.println("Data received is : " + data );
   }
}

Let us compile and run the above program, this will produce the following result:

Data received is : hello
Advertisements