我正在通过TCP发送文件,并让服务器发送包含" END_OF_MESSAGE"的消息。提醒客户端他们已收到整个文件并可以关闭套接字。正在发送文件,客户端收到" END_OF_MESSAGE"但是,当我使用strcmp将收到的信息与" END_OF_MESSAGE"进行比较时,它永远不会说它们匹配。我已经尝试过strncmp和memcmp但我很困惑为什么strcmp没有告诉我字符串匹配。
代码段:
服务器:
char endMessage[MESSAGESIZE] = "END_OF_MESSAGE";
if ((send(clntSocket, endMessage, sizeof endMessage, 0))!= sizeof endMessage) DieWithError("Sending failed");
以上代码段确实已发送。
客户端:
if ((bytesRcvd = recv(sock, echoBuffer, RCVBUFSIZE - 1, 0)) <= 0)
DieWithError("recv() failed or connection closed prematurely");
totalBytesRcvd += bytesRcvd; /* Keep tally of total bytes */
echoBuffer[bytesRcvd] = '\0'; /* Terminate the string! */
if (!(strcmp(echoBuffer, "END_OF_MESSAGE")==0)){
printf(echoBuffer); /* Print the echo buffer */
printf("\n");
}else{
break; //break out of while loop
}
echoBuffer的strcmp和&#34; END_OF_MESSAGE&#34;永远不会返回0,即使&#34; END_OF_MESSAGE&#34;是我从服务器发送的东西..我已经尝试过strncmp比较前3个字符(&#34; END&#34;)无济于事。
注意:当我打印出echoBuffer时,最后一个打印出END_OF_MESSAGE,这只会增加我的困惑。
有没有人对我做错了什么有任何见解?
谢谢。
答案 0 :(得分:1)
am sending a file through TCP, and have the server sending a message containing "END_OF_MESSAGE" to alert the client that they have received the whole file and can close the socket.
Why? Just close the socket. That will tell the client exactly the same thing..
What you're attempting is fraught with difficulty. What happens if the file contains END_OF_MESSAGE
? You're going to need an escape convention, and an escape for the escape, and inspect all the data when both sending and receiving.
The actual problem that you're seeing is that END_OF_MESSAGE can arrive along with the last bit of the file, so it isn't at the start of the buffer.
But it's all pointless. Just close the socket.