简体   繁体   中英

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?

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());
}

An ObjectOutputStream writes primitive data types and graphs of Java objects to an OutputStream. The objects can be read (reconstituted) using an ObjectInputStream. Persistent storage of objects can be accomplished by using a file for the stream. If the stream is a.network socket stream, the objects can be reconstituted on another host or in another process.

A data output stream lets an application write primitive Java data types to an output stream in a portable way. An application can then use a data input stream to read the data back in." You don't need to write primitive data types in binary, so do not use DataOutputStream

An OutputStreamWriter is a bridge from character streams to byte streams: Characters written to it are encoded into bytes using a specified charset. The charset that it uses may be specified by name or may be given explicitly, or the platform's default charset may be accepted.

You need to create an OutputStreamWriter for sending json objects to the client

OutputStreamWriter out = new OutputStreamWriter(socket.getOutputStream());
JSONObject obj = new JSONObject();
obj.put("name", "harris");
obj.put("age", 23);
out.write(obj.toString());

You can read the output data from the client using InputStreamReader by this way

InputStreamReader input = new InputStreamReader(socket.getInputStream());
int data = input.read();
while (data != -1) {
    System.out.print((char)data);
    data = input.read();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM