Curently I`m developing chat aplication using C and libevent library for both client and server. I started from simple prototype, where client simply send plain string, server recive it and send it to every connected user except the sender. But now I need to send not only the string, but also some information about the user, for example - his name. So, what the best wey to send complicated data (structs for exmaple) through sockets in C?
I have some code, that sends and recives structure as byte array, but i dont know, is it right to send it like that, or better to use JSON serialization for example. Thanks.
Client method, that read line and send it to server:
void *readmsg_and_send_msg(void *arg)
{
struct client *cl = (struct client *)arg;
struct sock_data data;
uint8_t sendbuff_array[DATA_BUFF_LENGTH];
data.type = SENDMSG_REQUEST;
char *line;
while (1)
{
line = getline();
if (line)
{
memcpy(data.data, (void *)line, strlen(line));
memcpy(sendbuff_array, &data, sizeof(data));
printf("%s\n", (char *)sendbuff_array);
bufferevent_write(cl->buf_ev, (void *)sendbuff_array, sizeof(sendbuff_array));
}
}
}
Server "on read" method:
void buffered_on_read(struct bufferevent *bev,
void *arg)
{
struct client *this_client = arg;
struct client *client;
sock_data_t *sockdata;
uint8_t data[DATA_BUFF_LENGTH];
size_t n;
/* Read 8k at a time and send it to all connected clients. */
for (;;)
{
n = bufferevent_read(bev, &data, sizeof(data));
//if 0 - end reading
if (n <= 0)
break;
}
sockdata = (sock_data_t *)data;
if (sockdata->type == SENDMSG_REQUEST)
{
printf("\033[0;36mNew message %s from %d recived\033[0m\n", (char *)sockdata->data, this_client->fd);
TAILQ_FOREACH(client, &client_tailq_head, entries)
{
if (client != this_client)
{
bufferevent_write(client->buf_ev, (void *)sockdata->data, sizeof(sockdata->data));
printf("Message %s successfully sended to user %d\n", (char *)sockdata->data, client->fd);
}
}
}
else
{
printf("%s - %d\n", (char *)sockdata->data, sockdata->type);
printf("Unimplemented request type\n");
return;
}
}
Struct, that I`m trying to send/recive:
#pragma pack(push, 1)
typedef struct sock_data_s
{
request_type_e type;
uint8_t data[DATA_BUFF_LENGTH];
} sock_data_t;
#pragma pack(pop)
Where request_type_e - enum, using for definding type on incoming request:
typedef enum request_type
{
REG_REQUEST = 0x0, //registration request
LOG_REQUEST, // login request
GETMSG_REQUEST, // get list of room`s messages request
SENDMSG_REQUEST, // send message to room
} request_type_e;