server.c
if (retSize == -2)
{
if (send(client_sock, buf, BUF_SIZE, 0) == -1)
{
close_socket(client_sock);
close_socket(sock);
fprintf(stderr, "Error1 sending to client.\n");
return EXIT_FAILURE;
}
printf("You have sent %d msg\n", cntOfMsg);
printf("The msg is:\n %s\n", buf);
printf("------------\n");
}
else
{
if (send(client_sock, ret, BUF_SIZE, 0) == -1)
{
close_socket(client_sock);
close_socket(sock);
fprintf(stderr, "Error2 sending to client.\n");
return EXIT_FAILURE;
}
printf("You have sent %d msg\n", cntOfMsg);
printf("The msg is:\n %s\n", ret);
printf("------------\n");
}
client.c
while ((bytes_received = recv(sock, buf, BUF_SIZE, 0)) > 1)
{
buf[bytes_received] = '\0';
printf("You have received %d msg\n", cnt);
fprintf(stdout, "Received:\n%s\n", buf);
printf("-----------\n");
memset(buf,0,sizeof(buf));
}
Part of the output is as shown below:
NOTICE:
output like "Can't write error_log" or "syntax error" have nothing to do with the problem.Your can believe the code I show is the only place where send or recv.
CodePudding user response:
TCP send can segment the data however it wants. If you send small buffers, TCP can group them and send them as a single packet after a timeout or a pending ack is received. If you send large buffers, TCP can break them into a series of smaller packets, favoring TCP segmentation over IP fragmentation.
TCP recv can theoretically return only 1 byte, even if you think there should be more data waiting.
When using TCP to send records, you need to use a record layer that prepends each record with its length (say, a 32-bit integer in big-endian order). The receiver must then accumulate a length (which could theoretically dribble in 1 byte at a time), and then accumulate the record content described by that length. The receiver ping-pongs between accumulating a length and accumulating record content.
In a line-oriented protocol, you could use a newline character to delineate record boundaries. It's really up to you to decide how to indicate boundaries within the TCP byte stream.
CodePudding user response:
On each recv()
, you are just incrementing the cnt
variable and printing, it doesn't represent the number of bytes received. Try printing the bytes_received
instead.
In the same way, in the send()
part, print the return value of send()
call instead of cntOfMsg