How do you send Json object's through sockets preferable through ObjectOutputStream class in java this is what I got so far
s = new Socket("192.168.0.100", 7777);
ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream());
JSONObject object = new JSONObject();
object.put("type", "CONNECT");
out.writeObject(object);
But this gives an java.io.streamcorruptedexception exception any suggestions?
Instead of using ObjectOutputStream
, you should create an OutputStreamWriter
, then use that to write the JSON text to the stream. You need to choose an encoding - I would suggest UTF-8. So for example:
JSONObject json = new JSONObject();
json.put("type", "CONNECT");
Socket s = new Socket("192.168.0.100", 7777);
try (OutputStreamWriter out = new OutputStreamWriter(
s.getOutputStream(), StandardCharsets.UTF_8)) {
out.write(json.toString());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With