I want to send json over a socket stream but I constantly encounter this error, when closing the connection and I have no idea why. I am trying to close a JsonWriter and I get an IOException even though I never used the JsonWritter. Here is the exception in question:
Exception in thread "main" java.lang.RuntimeException: java.io.IOException: Incomplete document
at Main.close(Main.java:34)
at Main.socketTest(Main.java:23)
at Main.main(Main.java:12)
Caused by: java.io.IOException: Incomplete document
at com.google.gson.stream.JsonWriter.close(JsonWriter.java:610)
at Main.close(Main.java:31)
... 2 more
And this is the code for the server socket:
public class Main {
public static void main(String[] args) {
Main main = new Main();
main.socketTest();
}
Socket socket;
JsonWriter jsonWriter;
public void socketTest() {
try (ServerSocket serverSocket = new ServerSocket(3030)){
Socket socket = serverSocket.accept();
this.socket = socket;
jsonWriter = new JsonWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"));
jsonWriter.close();
socket.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
The client code is very basic and it justs establishes connection with server:
public class ClientTest {
public static void main(String[] args) {
ClientTest clientTest = new ClientTest();
clientTest.connect();
}
public void connect() {
try {
Socket socket = new Socket("localhost", 3030);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
I hope anyone can help me because I have been struggling with this issue for days.
An "empty" stream or string is not a valid JSON document for the com.google.gson.stream.JsonWriter
class:
To encode your data as JSON, create a new
JsonWriter
. Each JSON document must contain one top-level array or object.
So you must write an array or object, otherwise you get the "Incomplete document" error message as indicated in documentation of close()
:
Throws:
IOException
- if the JSON document is incomplete.