Reputation: 528
I'm trying to implement a small application (server & client) which should communicate over Ethernet.
I defined my own "protocol" for the communication between server and client.
Now I'm having some troubles with the implementation of this protocol on the client side (written in C). I prefer to implement a general receive function. This function should receive a fix-size "header". In this header, the "Payload size" and "Payload type" is defined. My receive function allocates the required memory and receives the full Payload.
So far so good. But now I will assign the received data to a specific type. I defined different struct (one for each Payload type). When the struct includes only primitives data types (integers) it works well. But when I have a mixed type (integers and char* for a message) I have some troubles with the access to the string.
A small example: The received Payload in the memory looks like:
----
int (e.g. 0x42)
----
int (e.g. 0x42)
----
char (e.g. 'o')
----
char (e.g. 'k')
----
char (e.g. '\0')
----
For this I defined a struct:
typedef struct {
int error;
int obj;
char* message;
} payload;
I assign the receive data with the following cast:
payload* myPL = (payload*) receviedPayload;
The casting works for the integer values, but not for the message. I see the problem with the char* (pointer) and only the char type. But I don't have an idea how I can do this cast... Furthermore, I prefer to use the data in the receive buffer and not to copy the data.
Does anyone know how I can do this? Or does anyone have any general ideas for an implementation of a socket communication with different payloads and data types?
Thanks!
Upvotes: 1
Views: 535
Reputation: 21
If you want to use the data in the receive buffer, with no copy, one way to do this is to send a string with constant size.
typedef struct {
int error;
int obj;
char message[MESSAGE_SIZE];
} payload;
Upvotes: 1