Data transfer over sockets[TCP] how to pack multiple integer in c/c++ and transfer the data with send() recv()?

前端 未结 4 930
感情败类
感情败类 2021-01-21 19:17

I\'m making a small client/server based game, on linux in c/c++ and I need to send the player turn to the server.

Here is my problem.

I want to send two integer

4条回答
  •  爱一瞬间的悲伤
    2021-01-21 19:37

    If all your messages are expected to be of same length, then you do not need a message header. Something like that given below should work fine. In general you should be prepared to receive less or more than your expected message, as well as for one message to be split across many receives.

    Also, I would recommend one function that receives bytes making no assumption about what they mean, and another that interprets them. Then the first one can be applied more broadly.

    Treat the following only as pseudo code. not tested.

       // use a buffer length double of MESSAGE_LENGTH.
       static int offset = 0; // not thread safe.
       // loop to receive a message.
       while(offset < MESSAGE_LENGTH) {
           byte_count = recv(sock, &buf[offset],  (sizeof(buf)-offset), 0);
           if(byte_count > 0) {
              offset += byte_count;
           }
           else {
              // add error handling here. close socket.
              break out of loop
           }      
       }
       //  process buf here, but do not clear it.
       //  received message always starts at buf[0].
       
       if(no receive error above) {
           process_received_message(buf); // 
       }
    
       // move part of next message (if any) to start of buffer.
       if(offset > MESSAGE_LENGTH) {
            // copy the start of next message to start of buffer.
            // and remember the new offset to avoid overwriting them.
            char* pSrc = &buf[MESSAGE_LENGTH];
            char* pSrcEnd = &buf[offset];
            char* pDest = buf;
            while(pSrc < pSrcEnd){
               *pDest++ = *pSrc++;
            } //or memcpy.    
            offset -= MESSAGE_LENGTH;
       } 
       else {
            offset = 0;    
       }
    

提交回复
热议问题