I have a question about reading bytes from server socket.
I’m using the default values for literacy 8192b bytes on the network.
The problem is that there are times you need to send files larger than the buffer capacity.
To avoid increasing the buffer as you can know that those packets arriving at different times are related?
Client side snippet:
{
String c = xxxxx //imagine that it an string format JSON with 64000bites length
OutputStream wsOS = socket.getOutputStream();
wsOS.write(new String(data,"UTF-8"));
wsOS.flush();
}
When server side received the JSON string:
{
byte[] buffer = new byte[8192];
int size = 0;
StringBuilder str = new StringBuilder();
size = wsIS.read(buffer);
if (size > 0) {
str.append(new String(buffer, "UTF-8")
.substring(0, size));
while (wsIS.available() > 0) {
size = wsIS.read(buffer);
str.append(new String(buffer, "UTF-8")
.substring(0, size));
}
}
}
Problem:
All string arrived in the server but in block 8192b – I can not concatenate the string because I don’t know if the last string JSON is part of the previews.
Even if you increase the buffer size there is no guarantee that the whole string will be read in a single call to
wsIS.read.What this means is that you must have some mechanism to know where the previous string has ends and new one begins. Some choices are as follows:
ObjectOutputStream/ObjectInputStream