TCP Server-Client大json

时间:2014-11-12 05:56:10

标签: java android json tcp

我目前已经连接了TCP服务器(java桌面应用程序)和客户端(android应用程序)。

我可以从客户端发送json字符串到服务器,从服务器发送到客户端,我的问题有时候我需要从服务器发送一个被剪切的大字符串。

这是我的代码:

服务器端

public void sendResponse(String response){
  PrintWriter writer = new PrintWriter(BufferedWriter(
                       new OutputStreamWriter(mClientSocket.getOutputStream())), true);

  if(writer != null && !writer.checkError()){
     writer.println(response);
     writer.flush();
  }
}

客户端

BufferedReader input = new BufferedReader(new InputStreamReader(mSocket.getInputStream()));
String response;
while((response = input.readLine()) != null && mRun){
    Data data = new Gson().fromJson(response, Data.class);
    //when i try to convert the response to Data object using Gson
    //it gives me a com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Unterminated array at line 1 column 106498

}

因为你可以看到客户端的错误发生,因为字符串很大,所以它被切断, 有人可以告诉我在这种情况下该怎么办?

提前感谢。

1 个答案:

答案 0 :(得分:4)

我建议您使用DataOutputStream而不是尝试读取线条。像,

public void sendResponse(String response) {
    OutputStream os = mClientSocket.getOutputStream();
    DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(os));
    dos.writeUTF(response);
    dos.flush();
}

然后,在客户端

InputStream is = mSocket.getInputStream();
DataInputStream dis = new DataInputStream(is);
String response = dis.readUTF(); // <-- not just one line. the entire string.
Data data = new Gson().fromJson(response, Data.class);

而且,如果它是真正的大型JSON响应,您可以考虑添加GZIPInputStreamGZIPOutputStream

DataInputStream dis = new DataInputStream(new GZIPInputStream(is));

DataOutputStream dos = new DataOutputStream(new GZIPOutputStream(os));

修改

public void sendResponse(String response) {
    OutputStream os = mClientSocket.getOutputStream();
    DataOutputStream dos = new DataOutputStream(new GZIPOutputStream(os));
    byte[] buff = response.getBytes("UTF-8");
    dos.writeInt(buff.length);
    dos.write(buff);
    dos.flush();
}

然后阅读,

InputStream is = mSocket.getInputStream();
DataInputStream dis = new DataInputStream(new GZIPInputStream(is));
int len = dis.readInt();
byte[] buff = new byte[len];
dis.readFully(buff);
String response = new String(buff, "UTF-8");
Data data = new Gson().fromJson(response, Data.class);