Как передать любой тип файла (JPG, PNG, DOCX ..) с помощью TransmitFile () Windows32 API C / C ++ - PullRequest
0 голосов
/ 04 мая 2020


Я боролся с передачей различных типов файлов, сейчас мне удалось отправить только большие текстовые файлы и PDF-файлы, содержащие только текст (без изображений, значков и т. Д.). Я хотел бы знать, как я могу передать все типы файлов, такие как JPG, PNG, DOCX, mp4, EXE и т. Д. c ....


Чтобы быть более точным c:
Передача файла изображения (474 ​​КБ) получает первый ответ 8 байт только по какой-то причине, а затем переполнение буфера. Но с большим файлом .txt размером 81 КБ, например, все передается отлично, без переполнения.

Ниже прилагаются примеры кода клиента и сервера:

Примечание:

- переменная «container» похожа на буфер для отправки на сервер.
- «Перейти к прыжку» - просто выход для продолжения соединения.
- "bzero" в клиентском коде - это просто упрощенное определение, которое я сделал для mimset для windows, поскольку оно не имеет bzero.


Большое спасибо за вашу помощь!

Клиент работает на Windows 10

            strcat(file_name,str_cut(buffer,9,100));
            strcat(container,file_name);
            //Send filename to server
            send(sock, container, sizeof(container), 0);
            if(container == NULL)
            {
                goto jump;
            }
            bzero(container,1024);```
            LPCSTR filename2 = file_name;
            HANDLE get_file = CreateFile(filename2, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
            if(get_file == INVALID_HANDLE_VALUE)
            {
                strcat(container,"Error 8");
                send(sock, container, sizeof(container), 0);
                goto jump;
            }
            ULARGE_INTEGER ul;
            ul.LowPart = GetFileSize(get_file, &ul.HighPart);

            if ((ul.LowPart == INVALID_FILE_SIZE) && (GetLastError() != 0))
            {
                strcat(container,"Error 9");
                send(sock, container, sizeof(container), 0);
                goto jump;
            }

            OVERLAPPED ov = {};
            ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
            if (!ov.hEvent)
            {
                strcat(container,"Error 10");
                send(sock, container, sizeof(container), 0);
                goto jump;
            }

            unsigned __int64 uiPos = 0;
            unsigned __int64 uiRemaining = ul.QuadPart;

            while (uiRemaining > 0)
            {
                ul.QuadPart = uiPos;

                ov.Offset = ul.LowPart;
                ov.OffsetHigh = ul.HighPart;

                DWORD dwNumToSend = (uiRemaining >= 1024) ? 1024 : (DWORD)uiRemaining;

                if (!TransmitFile(sock,get_file, dwNumToSend, 0, &ov, NULL, 0))
                {
                    if ((GetLastError() != ERROR_IO_PENDING) && (WSAGetLastError() != WSA_IO_PENDING))
                    break;

                    WaitForSingleObject(ov.hEvent, INFINITE);
                }

                uiPos += dwNumToSend;
                uiRemaining -= dwNumToSend;
                //Sleep(1);
            }
            CloseHandle(ov.hEvent);
            CloseHandle(get_file);  


Сервер работает на Linux

            FILE * new_file = NULL;
            char fileName[30];
            bzero(fileName,30);
            //File name
            recv(client_socket,response, sizeof(response), 0);
            strcat(fileName,response);

            if( fileName == NULL)
            {
                printf("Error Downloading file \n");
                goto jump;  
            }
            char full_path[30] = "./data/";
            strcat(full_path,fileName);
            new_file = fopen(full_path, "w");
            if (new_file ==  NULL)  
            {
                printf("Unable to create file! \n");
                printf("Maybe check your spelling.. \n");
                goto jump;

            }
            printf("Downloading file to the data directory -->  %s \n",fileName);

            int len = 0;
            bzero(response,18384);  
            recv(client_socket,response,sizeof(response),0);

            if (!strcmp(response,"Error 8"))
            {
                printf("Error opening file on client side or doesn't exist! \n");
                fclose(new_file);
                goto jump;
            } 
            else if (!strcmp(response,"Error 9"))
            {
                printf("Unable to get filesize!");
                fclose(new_file);
                goto jump;
            }
            else if (!strcmp(response,"Error 10"))
            {
                printf("Unable to create Event!");
                fclose(new_file);
                goto jump;
            }
            //First write to file!
            fwrite(response,sizeof(response),1,new_file);

            len = strlen(response);
            printf("Response 0 %i \n", len);
            if (len < 1024)
            {
                printf("Successfully downloaded file! \n");
                fclose(new_file);
                goto jump;
            }
            bzero(response,18384);
            //From second packet
            len = 0;
            if(recv(client_socket,response,sizeof(response),0) > 0);
            {
                fclose(new_file);
                len = strlen(response);
                printf("Response 1 %i \n", len);
                new_file = fopen(full_path,"a");
                while(len > 0)
                {
                    fputs(response,new_file);
                    bzero(response,18384);
                    len = 0;
                    recv(client_socket,response,sizeof(response),0);
                    len = strlen(response);
                    printf("Response 2 %i \n", len);
                    if (len < 1024)
                    {
                        fputs(response,new_file);
                        bzero(response,18384);
                        break;
                    }
                }
            }
            bzero(response,18384);
            printf("Successfully downloaded file! \n");
            fclose(new_file);
            goto jump;
...