gpt4 book ai didi

java - TCP 服务器-客户端大 json

转载 作者:可可西里 更新时间:2023-11-01 02:45:21 25 4
gpt4 key购买 nike

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

我可以从客户端向服务器发送 json 字符串,也可以从服务器向客户端发送 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

}

如您所见,客户端发生错误是因为字符串太大,所以被截断了,有人可以告诉我在这种情况下该怎么做吗?

提前致谢。

最佳答案

我建议你使用 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);

关于java - TCP 服务器-客户端大 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26880241/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com