我遇到了Winsock2包裝類(客戶端 - 服務器)的問題,經過無數個小時的搔癢 - 我的頭在混亂,我決定,如果我問你的意見。C++,Send()函數發送額外的字節
更具體地說,問題是每次使用我的Send()函數時,客戶端和服務器(並不總是)會發送一個或兩個額外的字節!
例如,我使用SendBytes(「Hello」),Recv函數在字符數組的末尾使用'•'或其他隨機字符返回「Hello•」。
//main.cpp (Client)
#include "Socket.h"
int main()
{
NetworkService::Client cService = NetworkService::Client();
int res = cService.Initialize("127.0.0.1","20248");
if(res == 0){
int local = cService.SendBytes("Hello!");
printf("Bytes Sent: %ld\n", local);
cService.Shutdown();
char* temp = cService.Recv();
printf("String Recieved: %s - Size: %d",temp,strlen(temp));
printf("\nSTRLEN: %d",strlen("X5"));
}
else{
cService.Clean();
}
cService.Close();
while(!kbhit());
return 0;
}
當然,服務器發送字符串 「X5」,並在客戶端打印strlens ...
//The result with "X5" as the dummy text:
String Recieved: X5? - Size: 3 //Notice the extra '?' character
STRLEN: 2
發送//收到功能
int NetworkService::Client::SendBytes(char* lData){
int local = send(ConnectSocket, lData, (int)strlen(lData), 0);
if (local == SOCKET_ERROR) {
Close();
return WSAGetLastError();
}
return local;
}
char* NetworkService::Client::Recv(){
recv(ConnectSocket, recvbuf , recvbuflen, 0);
return recvbuf;
}
幫助,將不勝感激^ _ ^。
你沒有發送字符串中的終止NUL字節。 –
非常感謝您回答如此之快!繼承人的事情,我在字符串的末尾添加了'\ 0',但它沒有做任何事情。我仍然得到隨機插入。 – Christian
@christian:通過字符串文字,你已經有一個隱式的\ 0。爲了發送它,你需要在send()調用中調整size參數。將其從strlen(lData)更改爲strlen(lData)+1以包含結尾的\ 0。如果您仍然不確定爲什麼這是必要的,請務必查看[strlen()](http://cplusplus.com/reference/clibrary/cstring/strlen/)函數。 – ComicSansMS