简体   繁体   中英

Why doesnt java tcp socket send all data when called repeatetly in a while-loop?

I am sending data over a socket but the java socket seems to change ordering and loose data and I can't fix it. Here is my java code:

Socket socket;
...
while(isSending){
  try {
    DataOutputStream out = new DataOutputStream(socket.getOutputStream());
    String data = getMyData();
    out.writeBytes(data);//data is a csv string parsed on server-side
    out.flush();
  } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }
}

Server.cpp:

while(1){
    char recv_buffer[4096];
    memset(recv_buffer,0,4096);
    //receive data from socket
   int ret = recv(socket , recv_buffer , 4095 , 0);
   if (ret == 0){
      error_print("Socket not connected");
      ret = 0;
   } else if (ret < 0) {
      error_print("Error reading from socket!");
      ret = 0;
   }
  if(ret<=0) break;
  recv_buffer[ret]='\0';

  //parse recv_buffer
}

If I put a Thread.sleep(2000) in the java while-loop, the values are received correctly. What could be the reason for this behavior and how can I fix it?

Just as I suspected. You are completely ignoring the value returned by the recv() function. It can be -1 indicating an error, or zero indicating end of stream, or a positive integer indicating the length received. Instead you are assuming not only that the read aucceeded but also that it returns a null-terminated string.

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