Sending and receiving std::string over socket

前端 未结 4 761
故里飘歌
故里飘歌 2020-12-09 11:08

I have seen similar question on SO but non answers my question. Here I am trying to send and recv string:

I am sending std::string :

if( (bytecount=         


        
4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-09 11:31

    The best way is to send the length of the string data first in a fixed format (e.g. a uint32_t in network byte order). Then the receiver can read this first and allocate a buffer of the appropriate size before receiving the serialized message that is send afterwards.

    sd and csd are assumed to be already present socket descriptors.

    Sender.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 
    

    Receiver.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 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
    

    Advantage is. you don't have to mess around with multiple buffered reads and copying to the received string. Additionally you'll know at the receiver side when the sent data is finally complete.

    Disadvantage is, you're introducing kind of a 'protocol' when sending the length first.

提交回复
热议问题