justintime
justintime

Reputation: 101

Java: send JSON over UDP

how do I send a JSONObject in Java over UDP?

For TCP I use my following code:

private OutputStreamWriter outStreamW;

public void sendToConsumer(JSONObject jsonOb, Socket tcpSocket) {
    try {
        outStreamW = new OutputStreamWriter(tcpSocket.getOutputStream(), StandardCharsets.UTF_8);
        outStreamW.write(jsonOb.toString() + "\n");
        outStreamW.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

However I miss the approach as I implement it over UDP

Upvotes: 0

Views: 7253

Answers (1)

Attersson
Attersson

Reputation: 4876

1) serialize the JSON (e.g. convert to string)

2) divide in packets depending on the size (e.g. split the string)

3) send UDP packets

The receiver might receive only a few packets and, even if it receives all, it does in whatever order. You might want to add some leading number like 1/5 2/5 3/5 etc in case you have 5 packets. This is just an idea. I would stick to TCP.

Also, you would have to add some timeout within the deserialization logic.

Upvotes: 2

Related Questions