Recv总是少收1个字节

时间:2014-07-21 19:40:55

标签: c++ winsock recv

我真的厌倦了这个 - 我试着修复它大约5个小时,我仍然无法找到问题,也许你们可以。

我的问题是,当我从服务器发送IP时,客户端的recv总是会减少一个字节。服务器总是发送正确的数据和正确的数据,客户端的IP地址总是没有1号码,它始终是服务器发送的第一个:

192.168.0.101

客户收到:

92.168.0.101

同样重要的是始终收到客户的名字而没有任何问题 - 它只发生在IP地址上。

仔细看看:

服务器端发送数据[2个字符串 - 第一个是客户端名称,第二个是他的IP地址]:

j是循环thourght所有客户端的列表迭代器,客户端变量是要求所有客户端数据的变量

std::cout << j->client_name << " ";
int lenght = j->client_name.length()+1 ; //+1 for '\0' byte at the client buffer
std::cout << "Lenght (+1): " << lenght << " ";
lenght = htonl(lenght); //change byte order to network
send(client->client_socket,(char*)&lenght,sizeof(int),0);
std::cout << "I have sent: " <<  send(client->client_socket,j->client_name.c_str(),j->client_name.length(),0) << std::endl;
std::cout << inet_ntoa(j->client_connection.sin_addr) << " "; //showing IP adress
unsigned lenght2 = strlen(inet_ntoa(j->client_connection.sin_addr))+1; //+1 for '\0' byte at the client buffer
std::cout << "Lenght (+1): " << lenght2 << " ";
unsigned realistic_lenght = lenght2;
lenght2 = htonl(lenght2);
send(client->client_socket,(char*)&lenght,sizeof(unsigned),0);
std::cout << "I have sent: " << send(client->client_socket,inet_ntoa(j->client_connection.sin_addr),realistic_lenght,0) << std::endl;

正如我在服务器端所说的那样,一切似乎都很好,这里是客户端接收数据的代码:

char* data_buffor;
int lenght = 0;
recv(data.client_socket,(char*)&lenght,sizeof(int),0);
lenght = ntohl(lenght);
std::cout << "I have received: " << lenght << std::endl;
data_buffor = new char[lenght];
if (data_buffor != NULL) std::cout << "ALLOCATION WAS SUCCESFULL" << std::endl;
std::cout << "I have received: " << recv(data.client_socket,data_buffor,lenght,0) << std::endl;
data_buffor[lenght-1] = '\0';
temp.client_name = data_buffor; // everything is fine here
delete data_buffor;
data_buffor = NULL;
unsigned lenght2 = 0;
recv(data.client_socket,(char*)&lenght2,sizeof(unsigned),0);
lenght2 = ntohl(lenght2);
std::cout << "I have received: " << lenght2 << std::endl; // I DONT KNOW WHY BUT HERE I GET CRAZY NUMBERS LIKE 3203 and I should get 14 with IP: 192.168.0.101 + one byte for '\0' I think that may be causing all problems but I have no idea how to fix it.
data_buffor = new char[lenght2];
if (data_buffor != NULL) std::cout << "ALLOCATION WAS SUCCESFULL" << std::endl;
std::cout << "I have received " << recv(data.client_socket,data_buffor,lenght2,0) << std::endl;
temp.client_ip_adress = data_buffor;
all_clients.push_back(temp);
delete data_buffor
data_buffor = NULL;

任何帮助都将受到高度赞赏。

1 个答案:

答案 0 :(得分:2)

当服务器发送客户端名称时,它发送length作为字符串+ 1的长度以包括终止NULL字符。但是,std::string::length()返回的值 NOT 包含终止NULL,因此服务器实际上并未向客户端发送终止NULL。当客户端然后读取名称时,它会读取IP地址的第一个字符作为名称的终止NULL,但是您从未注意到这一点,因为客户端使用data_buffor覆盖'\0'中的该字节而不是依靠服务器发送'\0'