Java.net.DatagramPacket.setData() Method



Description

The java.net.DatagramPacket.setData(byte[ ] buf) sets the data buffer for this packet. With the offset of this DatagramPacket set to 0, and the length set to the length of buf.

Declaration

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

public void setData(byte[] buf)

Parameters

  • buf - the buffer to set for this packet

Return Value

This method does not return any value.

Exception

  • NullPointerException - if the argument is null

Example

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

package com.tutorialspoint;

import java.net.*;

class DatagramPacketDemo {

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

      // create a DatagramSocket object
      DatagramSocket ds = new DatagramSocket();

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

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

      // create a String object with data to be sent
      String data = "hello";

      // convert String object to byte array
      buf = data.getBytes();

      // attach data in buf to datagram packet dp
      dp.setData(buf);

      System.out.println("Data being sent is : " + data );
   }
}

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

Data being sent is : hello
Advertisements