[英]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. 我正在通过套接字发送数据,但是java套接字似乎改变了顺序并丢失了数据,我无法修复它。 Here is my java code:
这是我的Java代码:
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: 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. 如果我在Java while循环中放入Thread.sleep(2000),则可以正确接收值。 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.
您完全忽略了recv()函数返回的值。 It can be -1 indicating an error, or zero indicating end of stream, or a positive integer indicating the length received.
它可以是-1表示错误,也可以是0表示流的结尾,也可以是正整数表示接收的长度。 Instead you are assuming not only that the read aucceeded but also that it returns a null-terminated string.
相反,您不仅假定读取成功,而且还假定它返回以空值结尾的字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.