最好的方法是首先以固定格式(例如uint32_t
网络字节顺序)发送字符串数据的长度。然后接收者可以先读取它并分配适当大小的缓冲区,然后再接收随后发送的序列化消息。
sd
并且csd
假定已经存在套接字描述符。
发件人.cpp
std::string dataToSend = "Hello World! This is a string of any length ...";
uint32_t dataLength = htonl(dataToSend.size()); // Ensure network byte order
// when sending the data length
send(sd,&dataLength ,sizeof(uint32_t) ,MSG_CONFIRM); // Send the data length
send(sd,dataToSend.c_str(),dataToSend.size(),MSG_CONFIRM); // Send the string
// data
接收器.cpp
uint32_t dataLength;
recv(csd,&rcvDataLength,sizeof(uint32_t),0); // Receive the message length
dataLength = ntohl(dataLength ); // Ensure host system byte order
std::vector<uint8_t> rcvBuf; // Allocate a receive buffer
rcvBuf.resize(dataLength,0x00); // with the necessary size
recv(csd,&(rcvBuf[0]),dataLength,0); // Receive the string data
std::string receivedString; // assign buffered data to a
receivedString.assign(&(rcvBuf[0]),rcvBuf.size()); // string
优点是。您不必弄乱多个缓冲读取并复制到接收到的字符串。此外,您将在接收方知道发送的数据何时最终完成。
缺点是,您在首先发送长度时引入了一种“协议”。