最善の方法は、最初に文字列データの長さを固定形式 (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
メリットは。複数のバッファリングされた読み取りと受信した文字列へのコピーをいじる必要はありません。さらに、送信されたデータが最終的に完了すると、受信者側でわかります。
欠点は、最初に長さを送信するときに「プロトコル」のようなものを導入していることです。