Search code examples
javaarraysdatagram

What's the best way to send an array through Datagram Packets?


Say I had a String: Hello! I have to do all this:

  1. Convert string into byte array
  2. Send byte array
  3. Convert it back to a string (for later use)

This is my code...

//Sender
String send = "Hello!";
byte[] data = send.getBytes();
DatagramPacket packetOut = new DatagramPacket(data, data.length); //send blah blah

//Receiver
//blah blah receive it
String receive = new String(packetIn.getData()); //convert it back

What's a quick and elegant way to do this for an array of integers?


Solution

  • For an int[] you can serialize using ObjectOutputStream but a faster way might be to use a ByteBuffer.

    public static byte[] intsToBytes(int[] ints) {
        ByteBuffer bb = ByteBuffer.allocate(ints.length * 4);
        IntBuffer ib = bb.asIntBuffer();
        for (int i : ints) ib.put(i);
        return bb.array();
    }
    
    public static int[] bytesToInts(byte[] bytes) {
        int[] ints = new int[bytes.length / 4];
        ByteBuffer.wrap(bytes).asIntBuffer().get(ints);
        return ints;
    }