-1

Here is my code:

  • Client

    Position pos(1.0,2.0,0.45);
    feedback feed(12, pos, 100);
    msgpack::sbuffer sbuf;
    msgpack::pack(sbuf, feed);          
    int test = write(tcp_client.sockfd, sbuf.data(),sizeof(sbuf));
    
  • Server :

    char* buffer = new char[41];
    int test = recv(TCP_server.newsockfd, buffer, 40, MSG_WAITALL );
    
    for (int i=0; i< sizeof(buffer); i++)
    std::cout << std::hex << (int)buffer[i] << " ";
    std::cout << std::endl;
    

For the other parts of the codes, connection is established and data has been transmitted successfully.

The problem now is that I got the following output :

  • Client :

    ffffff94 b c ffffff93 ffffffca 3f ffffff80 0 0 ffffffca 40 0 0 0 ffffffca 3e ffffffe6 66 66 64
    
  • Server :

    ffffff94 b c ffffff93 ffffffca 3f ffffff80 0
    

    Is there any reason why received data stopped after encountering the first 0x0000 char? when I send a string, everything works fine but not in this specific case.

For the records, the recv() doc doesn't help much...

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Vtik
  • 3,073
  • 2
  • 23
  • 38

1 Answers1

2

When you call recv, you should use the returned value from that function to determine the number of bytes you should process.

Instead, you used sizeof(buffer) to determine the number of times to loop, which is not correct. The buffer is a char *, and sizeof(char *) will usually be either 4 or 8, depending on 32 / 64 bit.

So this:

for (int i=0; i< sizeof(buffer); i++)

should be:

int test = recv(TCP_server.newsockfd, buffer, 40, MSG_WAITALL );
// assuming that test >= 0
for (int i=0; i < test; i++) 
PaulMcKenzie
  • 34,698
  • 4
  • 24
  • 45
  • ok , I seriously have to go to sleep ! half eye coding don't work ! thanks :) – Vtik May 19 '16 at 22:09
  • 1
    also note you are assuming that tcp is a message oriented protocol. ie you send 40 bytes and the receiver receives 40 byts in a chunk. TCP is stream oriented , you send bytes, the other end receives byts. The only guarantee is that all the bytes arrive and that they arrive in order. You have to loop on the receive to get all your 'message' – pm100 May 19 '16 at 22:22