0

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?

14
  • Maybe you are not getting data from stream as quickly as you are sending. Commented Jul 28, 2014 at 9:51
  • 1
    You should show the code that is reading the data. Commented Jul 28, 2014 at 9:51
  • @DarshanLila Isn't that EXACTLY what should NOT happen when using TCP sockets? Commented Jul 28, 2014 at 9:52
  • 1
    It does send all the data. The Java API and Posix require it. Your receiving code is where the bug is. Post it (edited into your question) and we'll show you where. Commented Jul 28, 2014 at 9:55
  • @DarshanLila TCP provides flow control. Your comment doesn't make sense. Commented Jul 28, 2014 at 10:01

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I added the detailed server code. If you know where in the code the reason for the in the question stated problem lies, please share.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.