Search code examples
javadatagram

Using DatagramPacket in Java


To send a String through a DatagramPacket we use:

 String msg = "example";
 byte[]data = msg.getBytes();
 DatagramPacket pktOut = new DatagramPacket(data, 0, data.length, dest, port)

How to send an array through a DatagramPacket ?

 int num[] = {50,20,45,82,25,63};
 //I need to send this over two packets, but I don't know how to deal
//with arrays when sending them

Thank you in advance


Solution

  • You could convert the Integer-array to a byte buffer using the ByteBuffer class.

    int num[] = { 50 , 20 , 45 , 82 , 25 , 63 };
    ByteBuffer bb = ByteBuffer.allocate( num.length * 4 );
    for ( int i : num ) {
        bb.putInt( i );
    }
    byte[] data = bb.array();