问题
I'm writing a console appication in cpp that sends control commands from a file via TCP to a host machine and receives a response. All those informations are shown on screen and logged to a file and this is the actual problem. The output string seems to store junk for any reason, even if I try to set a fixed length.
EDIT: cleaned up the code and took care of the return value of recv(). The only thing I don't get yet is that the 2nd recv line in my logfile is filled with junk. Maybe one of you guys is able to spot the problem.
string cmd="";
char *sendstr=(char*)cmd.c_str();
fflush(stdin);
int n = 1, total = 0;
char temp[1024];
string inStr;
if(cmdin.is_open())
{
while(!cmdin.eof())
{
total=0;
cmd=fread();
send(serverPC, sendstr, (int)strlen(sendstr),0);
n=recv(serverPC,&temp[total],sizeof(temp)-total-1,0); // FIX THIS
total+=n;
temp[total]='\0';
inStr=temp;
fwrite(inStr,cmd);
}
cout << "Data successfully sent!\n";
}
else{
cerr<<"can't find 'cmd.cfg' file"<<endl;
}
The output I expect :
<11:40:00> INIT
received: VELO=0.00km/h DOT=FORW
----
This is what i get :
<10:05:56> INIT
received: VELO=0.00km/h DOT=FORW
----
<10:05:56> VELO=50.00
received: VELO=0.00km/h DOT=FORW VELO=0.00km/h DOT=FORW VELO=0.00km/h
DOT=FORW VELO=0.00km/h DOT=FORW VELO=0.00km/h DOT=FORW VELO=0.00km/h DOT=FORW
VELO=0.00km/h DOT=FORW
----
<10:05:56> VELO=100.00
received: VELO=50.00km/h DOT=FORW
----
<10:05:56> DOT=BACK
received: VELO=50.00km/h DOT=FORW
回答1:
A key point to remember when writing a TCP receiver is that TCP is considered as a data stream. This means that when you perform a receive from something sending packets of N bytes of data, you can receive:
- N bytes of data
- less than N bytes of data
- more than N bytes of data
Assuming there is no disconnection, buffer overflow, or other error, you will always receive what the server sends, in the order it sends it, but messages may be truncated or concatenated at the receiving end. It's one of the reasons that a lot [citation needed?] of custom TCP protocols include either a length field (so you know how much data you need to receive), or some way of denoting the end of the data. That way your receiver can loop until it has received just the right amount, leaving the rest in the TCP buffer for the next receive.
When you say you are seeing "junk", it doesn't look like junk to me, it looks like several packets of data concatenated together into one.
来源:https://stackoverflow.com/questions/15925158/c-winsock-recv-buffer-junk