Java.net.DatagramPacket.setData() Method



Description

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

Declaration

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

public void setData(byte[] buf, int offset, int length)

Parameters

  • buf - the buffer to set for this packet

  • offset - the offset into the data

  • length - the length of the data and/or the length of the buffer used to receive data

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 array to Datagram packet dp with
      // 1 as offset and length 2
      dp.setData(buf, 1, 2);

      String str = "Data being sent using offset and length is : " + data.substring(1,3) ;

      System.out.println( str );
   }
}

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

Data being sent using offset and length is : el
Advertisements