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

前端 未结 2 1160
遇见更好的自我
遇见更好的自我 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:34

    Go through you entire client and server code and fix:

    1) All those times where you do not handle correctly the results returned from system calls. This especially applies to the result returned by recv() which can be negative, (error), zero, (peer closed the connection), or some positive number less than, or equal to, the number of bytes requested - the ONLY WAY YOU CAN TELL FOR SURE HOW MANY BYTES HAVE BEEN READ IN TO THE BUFFER. Forget the number of bytes requested in the call and any memset/bzero before, and/or strlen/whatever after, it returns, they are all inadequate/misleading.

    2) All those times where you assume that, just because you request the recv() of X bytes and recv() returns a positive number, that number will be X.

    3) All those times that you call any str* C-style library calls on any buffers that are not 100% guaranteed to be NULL-terminated.

    0 讨论(0)
  • 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");
    
    0 讨论(0)
提交回复
热议问题