Search code examples
javakotlinudpdecodedatagram

Java/Kotlin UDP datagram


I have a very basic question. Imagine one has a simple udp client, which is listening to incoming datagrams. Those datagrams are just byte[], but they may contain complex information, like Strings, ints and so on.

Is there any elegant way of decoding the datagram like using a struct defining the datagram content and a union in C, instead of working through the received byte[] step by step with e.g. a ByteBuffer?

EDIT 1

Okay trying FlatBuffers now. I can build a testproject to play around a little. The first test I wanted to perform was to parse the simplest possible thing. Just one short (int16). I'm using this .fbs scheme

// Example IDL file for our monster's schema.

namespace UDPdatagram;


table DatContent {
    id:short;
}


root_type DatContent;

The minimal code I' trying to run is the following:

package controllingFXML

import UDPdatagram.DatContent
import java.nio.ByteBuffer

fun main() {
    // use a short (16 byte int, i.e. 2 byte)
    val byteArray           = ByteArray(2)
    // the test number
    val testShort: Short    = 67
    println("TEST SHORT: $testShort")

    // allocate a byte buffer and add the test short
    val buffer              = ByteBuffer.allocate(byteArray.size)
    buffer.position(0)
    buffer.putShort(testShort)

    // reset the position and verify its content
    buffer.position(0)
    val buffShort           = buffer.short
    println("BUFFER SHORT: $buffShort")

    // reset the position of the buffer again and try to use flatbuffers
    buffer.position(0)
    val content             =  DatContent.getRootAsDatContent(buffer)
    println("PARSED CONTENT: ${content.id()}")
}

Unfortunately I always get the following, when running the code:

Exception in thread "main" java.lang.IndexOutOfBoundsException
    at java.base/java.nio.Buffer.checkIndex(Buffer.java:688)
    at java.base/java.nio.HeapByteBuffer.getInt(HeapByteBuffer.java:392)
    at UDPdatagram.DatContent.getRootAsDatContent(DatContent.java:14)
    at UDPdatagram.DatContent.getRootAsDatContent(DatContent.java:13)
    at controllingFXML.AsdfKt.main(asdf.kt:25)
    at controllingFXML.AsdfKt.main(asdf.kt)

I'm totally lost. What am I missing here?


Solution

  • Either (i) ByteBuffer or (ii) DataInputStream wrapped around a ByteArrayInputStream, in both cases wrapped around the byte array. Or use DatagramSocketChannel directly with a ByteBuffer. – user207421