I'm writing a c++ client. The client connects to the server with TCP protocol successfully and sends data too. I wrote the code below to receive data :
char data[9];
int received_size = recv(fd, data, 9, flags);
std::string str{ data };
// str.empty() is true
Which flags is MSG_NOSIGNAL.
The problem is that after execution of this line the received_size is 9 but the data length is zero.
If recv
is returning a value, then that is the number of bytes received.
The issue is that you're using the wrong functions to determine the data that you're receiving. The std::string
constructor that you're using will stop at the first null byte, irrespective of the number of actual bytes recv
returned.
Instead, use the other version of the std::string
constructor that takes a byte length:
char data[9];
int received_size = recv(fd, data, 9, flags);
std::string str(data, received_size);