1

I have worked when both the ends of communication were based on erlang and documentation makes it clear that using {packet, N} appends a header with the size of the message and gen_tcp:recv/2 removes the header when receiving. This is pretty straightforward. However, if the receiving program is not erlang based, rather c++ based, how to I only parse the header and know the size of the message so that I can allocate that amount of memory. I used till now,

//Receive a message from client
while( (read_size = recv(sock , client_message , 2000 , 0)) > 0 )
{

    //end of string marker
    client_message[read_size] = '\0';
    write(sock , client_message , strlen(client_message));
    //clear the message buffer
    memset(client_message, 0, 2000);
}

But not sure how to get that header and then use the ei_module to get the real decoded value.

This is how I have been decoding the message.

code here This was when the client connected with the option {packet,0} so there was no header with size. To allow dynamic memory allocation, I am starting to use {packet, N} but unsure how to read that header? Thank you in advance.

Community
  • 1
  • 1
sad
  • 820
  • 1
  • 9
  • 16

1 Answers1

7

The {packet,N} option where N is one of 1, 2, or 4 puts a header on the sent data that is 1, 2 or 4 bytes in length, respectively. The header value is sent in network byte order.

To read the header in C++, first read N bytes from your C++ socket.

  • If N is 1, then the byte you read contains the packet size.
  • If N is 2, read the 2 bytes into a uint16_t, then convert the value to host byte order using ntohs, which will give you a uint16_t containing the packet size.
  • If N is 4, read the 4 bytes into a uint32_t, then convert the value to host byte order using ntohl, which will give you a uint32_t containing the packet size.

Once you have the packet size, you can then read the number of bytes it indicates in order to get the rest of the message and process it.

Steve Vinoski
  • 19,847
  • 3
  • 31
  • 46