I\'m doing a little project of TCP connection by C language, and the problem with my code is mentioned in the title. And the following is the uploading part of my code
C
The main problem is the (not) handling of the send()
return value, because even in the absence of any error condition, send()
may return a smaller value than requested (e. g. if a buffer is full). After each loop cycle in the client, you increment z
by the number of bytes read to buf
, but disregard that a smaller number of bytes may have been sent. This leads to the outcome that the client loop completes without having sent all data, despite of incorrectly saying so. Change that e. g. to:
printf("Uploading......\n");
while (z < filesize)
{
byteNum = fread(buf, sizeof(char), sizeof buf, fp);
printf("Bytes read to buf : %d\n", byteNum);
int sent = 0;
while (byteNum > 0)
{
int ret = send(serverSocket, buf+sent, byteNum, 0);
if (ret < 0) { perror("send"); goto fail; }
sent += ret, byteNum -= ret;
printf("Totally sent bytes: %d\n", z += ret);
}
}
printf("Upload completed.\n");