TCP server doesn't receive the right bytes number from client

前端 未结 2 1193
遇见更好的自我
遇见更好的自我 2021-01-26 03:20

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

2条回答
  •  自闭症患者
    2021-01-26 03:40

    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");
    

提交回复
热议问题