简体   繁体   中英

Sending large JSON files via sockets

Well this is embarassing. I am trying to send a large JSON file via sockets, and naturally the string exceeded the limit, so I tried compressing it, but for some strange reason I only get a single byte on the server-side. This is what I have so far:

Server-side:

StringBuilder sb = new StringBuilder();
String str;
while((str = request.getReader().readLine()) != null)
    sb.append(str);
Socket client = new Socket("localhost", 8081);

OutputStream outServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(new GZIPOutputStream(outServer));
byte[] buff = sb.toString().getBytes("UTF-8");
System.out.println(buff.length);
out.writeInt(buff.length);
out.write(buff);
out.flush(); 
client.close();

The length of buf is 198153 in the particular case that I am trying to make this work.

The client-side:

ServerSocket serverSocket = new ServerSocket(8081);
Socket server = serverSocket.accept();

DataInputStream in = new DataInputStream(new GZIPInputStream(server.getInputStream()));
System.out.println(in.available());
int len = in.readInt();
byte[] buff = new byte[len];
in.readFully(buff);
String response = new String(buff, "UTF-8");
System.out.println(response);

updateMessage(response);
server.close();
serverSocket.close();

the in.available() is just 1 in this case, and the program doesn't execute anymore, it just stops there (it doesn't terminate though) Any ideas? I thought that it might be helpful to get an outside perspective, because it might be something that I am missing out, something obvious. Thanks.

Since you are sending just one message per connection (which would be inefficient for small messages but for larger enough ones it doesn't matter so much) I would just send the entire message as text and read the whole message in one go.

NOTE: your code drops all newlines which I suspect wasn't intended.

For writing one message per connection.

try (Socket client = new Socket("localhost", 8081);
    Writer writer = new OutputStreamWriter(new GZIPOutputStream(client.getOutputStream()), "UTF-8")) {
    char[] chars = new char[8192];
    for (int len; (len = request.read(chars)) > 0;)
         writer.write(chars, 0, len);
}

for reading

try (Socket server = serverSocket.accept();
     Reader reader = new InputStreamReader(new GZIPInputStream(server.getInputStream()), "UTF-8")) {
     // read the text as above.
}

原来,我只需要删除GZIPInputStream和GZIPOutputStream,因此无论何时要发送带有套接字的大字符串,都可以随意使用此技术,我在Internet上也找不到任何其他/更好的方法。

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