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);
You are expecting the received data to be zero-terminated. Which is a wrong expectation because it can receive incomplete data. The correct way is to use received_size (after error checking has been done):
std::string str(data, received_size);
That still is not enough in real-world applications. You need to delimit messages somehow.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With