I have a client program that connects to two servers at the same time. To serialize the data I'm transferring through the sockets I created the following struct
:
typedef struct {
char origin[14];
char type;
char data[100];
}socket_data;
When connecting the client process to the servers, the client sends some information and waits to receive a response by both servers:
Client:
//...
//Sending info to both servers
socket_data station_info;
strcpy(station_info.origin, "DANNY");
station_info.type = 'C';
strcpy(station_info.data, config.station);
write(socket_jack, &station_info, sizeof(socket_data));
write(socket_wendy, &station_info, sizeof(socket_data));
//Getting servers response
socket_data response_jack, response_wendy;
read(socket_jack, &response_jack, sizeof(socket_data));
read(socket_wendy, &response_wendy, sizeof(socket_data));
/*DEBUGGING*/char str[150]; sprintf(str, "%s, %c, %s
", response_jack.origin, response_jack.type, response_jack.data);write(1, str, strlen(str));
/*DEBUGGING*/char st[150]; sprintf(st, "%s, %c, %s
", response_wendy.origin, response_wendy.type, response_wendy.data);write(1, st, strlen(st));
//...
Server 1 & Server 2 (same code for both):
//...
//Receiving clients info
socket_data station_info;
read(socket, &station_info, sizeof(socket_data));
//Sending a response to the client
if (station_info.type != 'C') {
socket_data response;
strcpy(response.origin, "JACK");
response.type = 'E';
strcpy(response.data, "ERROR");
write(socket, &response, sizeof(socket_data));
close(socket);
return 0;
} else {
socket_data response;
strcpy(response.origin, "JACK");
response.type = 'O';
strcpy(response.data, "CONNECTION OK");
/*DEBUGGING*/char str[150]; sprintf(str, "%s, %c, %s
", response.origin, response.type, response.data); write(1, str, strlen(str));
write(socket, &response, sizeof(socket_data));
}
As you can see, I've added some writes
for debugging purposes and when I execute the code, the ideal output I expect on the client side is:
JACK, O, CONNECTION OK
WENDY, O, CONNECTION OK
But instead, I'm getting something like:
, C, TION OK
WENDY, O, CONNECTION OK
or
JACK, O, CONNECTION OK
, C, TION OK
and sometimes it won't even print anything.
I'm guessing the socket buffer needs to be cleared up, but I'm not sure if that's the solution in here. How can I fix this or clear the socket buffer?