I have a C structures in two different machines - server and clients. For example:
struct account {
int account_number;
char *first_name;
char *last_name;
float balance;
};
My question is what are the possible ways to replicate the data between the machines? Maybe I can try to convert the data in XML and copy it? Or I can use arrays?
The simplest, most lightweight solution - if you have a connection open between the two machines in the form of a FILE* - may be to transmit with fprintf on one end, and decode with fscanf on the other.
protocol.h:
typedef struct _packet packet_t;
struct _packet {
int account_number;
char *first_name;
char *last_name;
float balance;
};
static const char packet_fmt[]=" acct: %d fname: %s sname: %s balance: %f";
sender:
...
printf(packet_fmt, acct, "Greg", "Benison", bal);
...
listener:
...
int n_read = fscanf(fin, packet_fmt, &acct, fname, sname, &balance);
if (n_read == 4)
printf("Received balance update for %s %s: %f\n", fname, sname, balance);
...
That may suffice for your four-field struct, but if you anticipate its structure changing or growing significantly it may make sense to pursue XML, JSON, or some other more formal encoding.
If you are familiar with C then I would use TCP sockets to transmit and receive your data. You will need to basically transmit your data though as raw bytes and in a specified order so you can decode it when received. You will need to allow for the endeanness of the machines and also you will need to send additional fields of data to specify the lengths of your variable length names (so that you know how many bytes to receive). Usually it is a good idea to add a field that indicates the total size of the data packet you are sending. Basically you can encode your data packet in anyway you choose and provided you unpack it in the same way at the other end your data will be transferred. Maybe this is an old hat way of doing things but I use this approach all the time in my day job to transfer data between machines. It is one of a number of options available to you. You could send data as xml of in other formats but sending raw bytes results in smaller packets (which may or may not be an issue you need to address). Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With