DatagramPacket

DatagramPacket defines several constructors. Four are shown here:

DatagramPacket(byte data[ ], int size)
specifies a buffer that will receive data and the size of a packet. It is used for receiving data over a DatagramSocket.
DatagramPacket(byte data[ ], int offset, int size)
specify an offset into the buffer at which data will be stored.
DatagramPacket(byte data[ ], int size, InetAddress ipAddress, int port)
specifies a target address and port, which are used by a DatagramSocket to determine where the data in the packet will be sent.
DatagramPacket(byte data[ ], int offset, int size, InetAddress ipAddress, int port)
transmits packets beginning at the specified offset into the data.

Useful DatagramPacket methods:

InetAddress getAddress( )
Returns the address of the source or destination.
byte[ ] getData( )
Returns the byte array of data contained in the datagram.
int getLength( )
Returns the length of the valid data contained in the byte array that would be returned from the getData( ) method.
int getOffset( )
Returns the starting index of the data.
int getPort( )
Returns the port number.
void setAddress(InetAddress ipAddress)
Sets the address to which a packet will be sent. The address is specified by ipAddress.
void setData(byte[ ] data)
Sets the data to data, the offset to zero, and the length to number of bytes in data.
void setData(byte[ ] data, int idx, int size)
Sets the data to data, the offset to idx, and the length to size.
void setLength(int size)
Sets the length of the packet to size.
void setPort(int port)
Sets the port to port.

The following demonstrates DatagramPacket and DatagramSocket in a server context.


import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class Main {
    final static int PORT = 10000;
    public static void main(String[] args) throws IOException {
        System.out.println("Server is starting");
        try (DatagramSocket dgs = new DatagramSocket(PORT)) {
            System.out.println("Send buffer size = " + dgs.getSendBufferSize());
            System.out.println("Receive buffer size = " + dgs.getReceiveBufferSize());
            byte[] data = new byte[100];
            DatagramPacket dgp = new DatagramPacket(data, data.length);
            while (true) {
                dgs.receive(dgp);
                System.out.println(new String(data));
                dgs.send(dgp);
            }
        } catch (Exception ioe) {
            System.err.println("I/O error: " + ioe.getMessage());
        }
    }
}

The following code demonstrates DatagramPacket and DatagramSocket in a client context.


import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class Main {

    final static int PORT = 10000;
    final static String ADDR = "localhost";

    public static void main(String[] args) {
        System.out.println("client is starting");
        DatagramSocket s = null;
        try (DatagramSocket dgs = new DatagramSocket()) {
            byte[] buffer;
            buffer = "Send me a datagram".getBytes();
            InetAddress ia = InetAddress.getByName(ADDR);
            DatagramPacket dgp = new DatagramPacket(buffer, buffer.length, ia,PORT);
            dgs.send(dgp);
            byte[] buffer2 = new byte[100];
            dgp = new DatagramPacket(buffer2, buffer.length, ia, PORT);
            dgs.receive(dgp);
            System.out.println(new String(dgp.getData()));
        } catch (IOException ioe) {
            System.err.println("I/O error: " + ioe.getMessage());
        }
    }
}

Multicasting

MulticastSocket describes a socket for the client or server side of a UDP-based multicasting session.


import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;

import java.net.MulticastSocket;

public class Main {

    final static int PORT = 10000;

    public static void main(String[] args) {
        try (MulticastSocket mcs = new MulticastSocket()) {
            InetAddress group = InetAddress.getByName("1.0.0.1");
            byte[] dummy = new byte[0];
            DatagramPacket dgp = new DatagramPacket(dummy, 0, group, PORT);
            int i = 0;
            while (true) {
                byte[] buffer = ("line " + i).getBytes();
                dgp.setData(buffer);
                dgp.setLength(buffer.length);
                mcs.send(dgp);
                i++;
            }
        } catch (IOException ioe) {
            System.err.println("I/O error: " + ioe.getMessage());
        }
    }
}
 
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

public class Main  {

    final static int PORT = 10000;

    public static void main(String[] args) {
        try (MulticastSocket mcs = new MulticastSocket(PORT)) {
            InetAddress group = InetAddress.getByName("1.0.0.1");
            mcs.joinGroup(group);
            for (int i = 0; i < 10; i++) {
                byte[] buffer = new byte[256];
                DatagramPacket dgp = new DatagramPacket(buffer, buffer.length);
                mcs.receive(dgp);
                byte[] buffer2 = new byte[dgp.getLength()];
                System.arraycopy(dgp.getData(), 0, buffer2, 0, dgp.getLength());
                System.out.println(new String(buffer2));
            }
            mcs.leaveGroup(group);
        } catch (IOException ioe) {
            System.err.println("I/O error: " + ioe.getMessage());
        }
    }
}
  
Home 
  Java Book 
    Networking  

DatagramPacket:
  1. DatagramPacket
  2. new DatagramPacket(byte[] buffer, int bufferLength)
  3. new DatagramPacket(byte[] buf, int length, InetAddress address, int port)
  4. DatagramPacket: getAddress()
  5. DatagramPacket: getData()
  6. DatagramPacket: getPort()
  7. DatagramPacket: getSocketAddress()