简体   繁体   English

无法收到服务器的完整响应

[英]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: 我正在使用Java套接字编程来接收服务器响应,正在使用char array并使用read()方法读取其中的每个响应:

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. 1-受影响的响应比其他响应大一点,但我确定它不会超过1000窝。

2- I'm pretty sure the server-side works perfectly and it sends the responses completed. 2-我很确定服务器端可以正常工作,并且可以发送完整的响应。

3- there isn't any type of terminators exist which could cause that behavior. 3-不存在任何可能导致该行为的终止符

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() . 您不应该假设您将在一次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. 一定不能依靠read()读取一条消息的全部,而不要读取任何下一条消息。

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) 自终止消息(例如XML,您可以通过到达其结束标记来告知文档的结尾)

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 . 此外,在构造InputStreamReader时,应指定要应用的编码。 Don't just use the platform default. 不要只使用平台默认值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM