Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send Json object through java sockets?

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?

like image 857
user3339626 Avatar asked Feb 22 '14 11:02

user3339626


1 Answers

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());
}
like image 91
Jon Skeet Avatar answered Sep 27 '22 18:09

Jon Skeet