0

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

justintime
  • 101
  • 2
  • 8
  • 3
    This doesn't strike me like you spent any time trying to find a solution yourself. http://idownvotedbecau.se/noresearch/ – f1sh May 30 '18 at 11:51
  • 1
    As an aside to your question, I don't think you should want to send JSON over UDP. You could potentially lose data in the process. – Francis Bartkowiak May 30 '18 at 11:53

1 Answers1

2

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.

Attersson
  • 4,755
  • 1
  • 15
  • 29