I am attempting to set up a server/client model. The client will receive two matrices from the user, then send these two matrices to the server, which will then compute their product and send the result back to the client, which shall print the result. I encode the matrices as a C-string and send them to the server, where it should be decoded. My code looks as follows:
The client sends the two matrices using the following code:
send_all( sockfd, send_str, strlen(send_str) );
shutdown( sockfd, SHUT_WR ); // Close the write side of socket, since sending is done.
Where send_all
is:
void send_all( int socket, char *data, size_t len )
{
size_t i;
for( i = 0; i < len; i += send( socket, data, len - i, 0 );
{
printf("%d bytes sent to server.\n", len - i); // To confirm send to user
}
}
My server then receives the the data as follows:
while( len = recv( connfd, buffer, MAX_LINE, 0 ) > 0 )
{
printf("%d bytes read.\n", len); // To confirm receive to user.
buffer[len] = '\0';
strcat(input, buffer);
}
if( len < 0 )
{
printf("Read error.");
}
The server then parses the string and computes the product, then sending the data in the same manner as the client, where the client receives the data in the same manner as the server.
When I run this program, the client prints that it has sent the correct number of bytes, for example:
406 bytes sent to server.
The server then prints (consistently, no matter the size of the string I send):
72720 bytes read.
and when attempting to print the string, it appears to be garbage.
I am running the client and server in separate Cygwin terminals, using the local host 127.0.0.1, and it appears that they connect successfully.
What am I doing wrong? Am I sending/receive the data in the correct manner? Will my method result in input
being identical to send_str
? Thank you for your help.
EDIT: I have seen many questions on here and else where addressing difficulties with send() and recv() but I have found no explanation of why recv would be returning such a large number when only a much smaller number of bytes are sent.