简体   繁体   中英

Server not receiving trailing longs in c++ socket

I am transferring a struct over socket using c++. I read some earlier questions on sending structs and one approach suggested was to transfer using a char* after cast. Since both server and client are on same machine so no issues of endianness here.

Couple of questions here. I get size of struct as 48. As per my calculation shouldn't it be 43? 8x4 + 10 +1

Secondly on server side when i print the received buffer I only get the text elements. The long integers are not received.

struct testStruct{
    char type;
    char field1[10];
    char field2[8];
    char field3[8];
    long num1, num2;
};


    testStruct ls;
    ls.type = 'U';

    strcpy(ls.field1, "NAVEENSHAR");
    strcpy(ls.field2, "abcd1234");
    strcpy(ls.field3, "al345678");
    ls.num1 = 40;
    ls.num2 = 200;
    char* bytes = static_cast<char*>(static_cast<void*>(&ls));
    bytes_sent = send(socketfd, bytes, sizeof(ls), 0);
    cout << "bytes sent: " << bytes_sent<< "\n";

    //On server sidechar
    incomming_data_buffer[1000];
    bytes_recieved = recv(new_sd, incomming_data_buffer,1000, 0);
    cout << "|" << incomming_data_buffer << "|\n";

It shows 48 bytes received and no trailing integers which i added. Any idea on why this could be happening. I have read about sending structs using boost serialization but at the same time that overhead is huge for simple structs.

You are almost certainly receiving all the data. The problem is with this line:

cout << "|" << incomming_data_buffer << "|\n";

which prints incomming_data_buffer as a C style string, so stops at the first zero-byte. Since your long values are encoded in binary for, there will be zeros at least there (there may also be zeros in the padding between fields).

You could try doing something like:

cout << "|";
for (int i = 0; i < bytes_received; i++)
{
    cout << hex << (((int)incomming_data_buffer[i]) & 0xff) << " ";
}
cout << "|\n";

to show all bytes of the package you received.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM