简体   繁体   中英

can't receive server full response

I'm using Java Socket Programming in order to receive server responses, I'm using a char array and read each response in it using read() method:

InputStream stream = null;
try{
    stream = socket.getInputStream();
}catch(Exception e){
    conn_lost();
}

if(stream != null){
    input = new BufferedReader(new InputStreamReader(
                    stream));

Looper.prepare();
char a[] = new char[1000];
for(int i =0; i < a.length; i++){
      a[i] = ' ';
   }

while (true){

   input.read(a);

   String response = String.valueOf(a);

   process_server_response(response);

   for(int i =0; i < a.length; i++){
         a[i] = ' ';
      }
}

The problem is some times I can't receive the full response from the server and instead of that I receive like half of it and then the response after that I receive the other half.

Worth to mention:

1- the affected response is a little large that other responses but I'm sure it's not exceed 1000 litters.

2- I'm pretty sure the server-side works perfectly and it sends the responses completed.

3- there isn't any type of terminators exist which could cause that behavior.

The problem is some times I can't receive the full response from the server and instead of that I receive like half of it and then the response after that I receive the other half.

Yes. That's how stream protocols work. You shouldn't assume that you'll receive all the data in a single call to read() .

If you have multiple messages on the same stream, you'll need a way of telling where a message ends. You must not rely on read() reading the whole of one message but not reading any of the next message.

The three common approaches are:

  • A length prefix for each message
  • A separator between messages
  • Self-terminating messages (eg XML, where you can tell the end of a document by reaching its closing tag)

If you don't have any of those schemes in place, but you want to put multiple messages on the wire and process them separately, your protocol is fundamentally broken and you should revisit it.

Additionally, you should specify the encoding to apply when constructing the InputStreamReader . Don't just use the platform default.

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