Java.net.DatagramPacket.setLength() Method



Description

The java.net.DatagramPacket.setLength(int length) sets the length for this packet. The length of the packet is the number of bytes from the packet's data buffer that will be sent, or the number of bytes of the packet's data buffer that will be used for receiving data. The length must be lesser or equal to the offset plus the length of the packet's buffer.

Declaration

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

public void setLength(int length)

Parameters

  • length - the length to set for this packet

Return Value

This method does not return any value.

Exception

  • IllegalArgumentException - if the length is negative of if the length is greater than the packet's data buffer length

Example

The following example shows the usage of net.DatagramPacket.setLength() 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);

      // set the length of data being sent to 3
      dp.setLength(3);

      String str = "Data being sent with fixed length 3 is : " + data.substring(0,3) ;

      System.out.println( str );
   }
}

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

Data being sent with fixed length 3 is : hel
Advertisements