Hi!
I have a server and a client program (both running on the same machine). The client is able to send a struct to the server with members such as "ID", "size" etc. Then I would like the server to send the ID-member (just an integer) back to the client as an ACK for validation, but I just can't figure this out despite being able to send the struct without problems..
Here is the code from server.c:
/* having just recieved the struct */
int ACK_ID = struct_buffer->message_ID;
result = send(CLIENT_socket, &ACK_ID, sizeof(int), 0);
if (result == -1) {
close(SERVER_socket);
printf("\n\t[ERROR] Failed to send ACK.\n");
exit(EXIT_FAILURE);
}
Here is the code from client.c:
// Recieve ACK from server
int ACK_ID;
com_result = read(CLIENT_socket, &ACK_ID, sizeof(int), 0);
if ((com_result == -1) || (ACK_ID != metablocks[index].message_ID)) {
printf("\n\t[ERROR] Failed to send metadata. ACK: %i\n", ACK_ID);
}
When I try to run this I get the following output from client.c:
[ERROR] Failed to send metadata. ACK: 14
And of course the server tells me it failed to send ACK. The value of the ID integer I'm trying to send should be 1, but it is recieved as 14. What am I doing wrong here?
Update
So I just tried what Mr. Shawley suggested, and got this error message:
Partial read: Undefined error: 0
First I tried exactly what he wrote, but then I noticed that the code is comparing com_result
with sizeof(int)
. So I assumed that was a typo and tried replacing com_result
with the ACK_ID
variable in the comparison. Same result.
Update 2
Just added a perror() on the server when it fails, and got the following error message:
Bad file descriptor
I am using the same socket for this operation as the one I used when receiving the struct. Here is an expanded code sample from server.c:
// Recieve connection
CLIENT_socket = accept(SERVER_socket, (struct sockaddr *)&CLIENT_address, &CLIENT_address_length);
if (CLIENT_socket == -1) {
close(SERVER_socket);
printf("\n\t[ERROR] Failed to accept client connection.\n");
exit(EXIT_FAILURE);
}
printf("\n\tClient connected!\n");
int data_size;
// Read meta data from connection
data_size = sizeof(struct msg_meta);
result = read(CLIENT_socket, &meta_buffer_char, data_size, 0);
meta_buffer = (struct msg_meta *) meta_buffer_char;
if (result == -1) {
close(SERVER_socket);
printf("\n\t[ERROR] Failed to read from connection.\n");
perror("\n\tRead");
exit(EXIT_FAILURE);
} else if (result > 0) {
printf("\n\tMessage recieved.\n");
printf("\n");
}
// Send ACK back to client
int ACK_ID = meta_buffer->message_ID;
result = send(CLIENT_socket, &ACK_ID, sizeof(int), 0);
if (result == -1) {
printf("\n\t[ERROR] Failed to send ACK.");
perror("\n\tSend");
printf("\n");
close(SERVER_socket);
exit(EXIT_FAILURE);
}
// Close sockets
close(SERVER_socket);
close(CLIENT_socket);