Hello! Now there is the last stage in my task. The server normally sends the blocks of the file to the client. It remains to glue them on the client side. The question is still purely theoretical: how will the client understand which file to create (with what extension) in order to record blocks received from the server?

Сервер //Отправка файла int i = 0; int b; int a = atoi(buffer); char * buff = new char[a]; d: while(!feof(in)) { b = fread(&buff[0],1,a,in); send(client_socket,&buff[0],b,0); i++; printf("Send %d block file \n", i); recv(client_socket, buffer, BUFFER_SIZE ,0); if (!strcmp(&buffer[0], "Принимаю поблочно файл!")) goto d; } fclose(in); printf("File successfully send clienty\n"); system("PAUSE"); Клиент //Прием файла else { f: int nbytes = recv( my_socket, &buff[0], sizeof(buff), 0 ); if ( nbytes == 0) { printf("\nПередача файла завершена\n"); system("pause"); fclose(RecFile); return -1; } if (nbytes < 0) { printf("Ошибка в передаче файла \n"); return -1; } RecFile = fopen ("C:/receve.txt","at"); fwrite(buff, 1, strlen(buff), RecFile); fclose(RecFile); strcpy(&buff1[0], "Принимаю поблочно файл!"); int n1 = strlen(buff1); send(my_socket, buff1, (n1-1), 0); goto f; } system("pause"); } 
  • We write the name of the file we are looking for - AnnaHatiko
  • What passion. Is it possible to add the text of the client and the server to the question (please, do not create a new question). - alexlz
  • @ AnnaHatiko, after sending all the blocks of the file, close the socket in the server. In the client, write to fwrite () exactly as many bytes as recv () returned. When recv () returns 0, the data has run out, just close the socket and the file in the client. - avp
  • Thanks, these problems are solved. Only the transfer I have now for .txt only works, what to do with other extensions? - AnnaHatiko 6:54
  • one
    And how, in fact, txt-file is fundamentally different from any other file? Only suffix. Through the socket, it doesn’t matter what data to transmit, binary or text. - dred

3 answers 3

@AnnaHatiko , sorry, but this (at least) is a strange code. Why do you take something from the client in the cycle of sending file blocks, and he (respectively) transmits. This is absolutely superfluous.

Apparently the following very simple exchange protocol would be correct:

 Cli: connect Cli->Serv: размер-блока имя-файла-завершающееся-нулем Serv->Cli: послать все байты файла, каждый send() посылает блок последний send() может послать меньше, чем блок Serv: close file, close socket Cli: close socket, close file 

There is no difference for types (file extensions)

     Сервер //Отправка файла int i = 0; int b; int a = atoi(buffer); char * buff = new char[a]; d: // зачем тут метка. Тут уже есть цикл while, // который благодаря d: -- goto d; вырождается в if while(!feof(in)) { b = fread(&buff[0],1,a,in); send(client_socket,&buff[0],b,0); i++; printf("Send %d block file \n", i); recv(client_socket, buffer, BUFFER_SIZE ,0); // это требование преподавателя? Или самостоятельное творчество? if (!strcmp(&buffer[0], "Принимаю поблочно файл!")) // Лишняя деталь. Если strcmp даёт 0, то возвращаетесь к началу цикла по goto, иначе -- переход по реализации while. goto d; // } fclose(in); printf("File successfully send clienty\n"); system("PAUSE"); Клиент //Прием файла else { f: // вполне заменяется циклом while ((nbytes = ...) > 0) int nbytes = recv( my_socket, &buff[0], sizeof(buff), 0 ); if ( nbytes == 0) { printf("\nПередача файла завершена\n"); system("pause"); fclose(RecFile); // А он уже закрыт. return -1; } if (nbytes < 0) { printf("Ошибка в передаче файла \n"); return -1; } RecFile = fopen ("C:/receve.txt","at"); // зачем его постоянно открывать/закрывать (да ещё перед каждым запуском удалять ручками)? fwrite(buff, 1, strlen(buff), RecFile); // Вместо strlen(buff) лучше бы nbytes fclose(RecFile); strcpy(&buff1[0], "Принимаю поблочно файл!"); // квитанция. Нафига, tcp это сам делает int n1 = strlen(buff1); send(my_socket, buff1, (n1-1), 0); // Отбрасываем ненужный восклицательный знак // Правильно, надо быть скромнее. goto f; } system("pause"); } 

    Well, somewhere like that.

    • all the same it is not clear RecFile = fopen ("C: /receve.txt", "at"); // why is it constantly open / close (and even before each launch delete handles)? And then where to write these blocks? And for any extensions, all the more .. - AnnaHatiko
    • So you open it before the start of the reception (and it is possible not to add ("a"), but to the record ("w") and after the end of the reception (nbytes == 0) close. Yes, and what is the problem with extensions? ( while I only see strlen (buff) for data containing null bytes) - alexlz
    • @ AnnaHatiko, as far as I can understand, you really have a problem in that the client and server work on the same computer, so the client cannot write to the file with the same name that he requested from the server. So? - If so, then let the client simply write the received files to another disk (for example, to a USB flash drive). Change the drive name in the client when you open the file, say, from C: to F: (or what kind of flash drive do you have?) For tests come down. - avp

    I heard about txt. Why do you open files as text? Open as binary. "ab" in fopen ("C: /receve.txt", "ab"); And the contents of the file should no longer concern you.

    Hmm, and this is not the client requests from the server file? Then he should know under what name to save.

    Yes, file reception is not very well done. Typically, programs of this type connect to the server, create the necessary file and download the contents.

    I look at the code and the TFTP, FTP and HTTP protocols are spinning in my head at the end. They are interesting in that they are as simple and widely used as possible and you can learn a lot from them.

    • Explain how these protocols are easier for Anna to create lab work. Especially TFTP, which generally should take into account the violation of the order of arrival of packages and their possible loss. And, by the way, remind, the description http how many pages it takes? "I know karate, judo, sambo, jujutsu and many more scary words" (c) Fomenko. - alexlz
    • No offense will be said, but their implementation is perceived more simply than the provided source code. Even the implementation of TFTP. There, by the way, the client (tsiska) simply requested parts of the file in order, the server gave what they asked for. Awesome and simple protocol, left an impression. I did not read the description of http, I do not know what volume there. The protocol itself is very simple. I have already written several servers. - mikelsv
    • Is it simpler than a lab @ AnnaHotiko? With tftp's retransmit? Monsieur understands perversions. Besides, I suspect that under the conditions of the problem it is necessary to use tcp, and there these tricks are already inside the protocol. - alexlz
    • Yeah. If you rewrite the lab @ AnnaHotiko, it will become easier, but now more difficult. TFTP server does not worry at all and gives the requested data. The client knows the size of the file, requested 10 parts, received, saved. If not received sends requests again. (I feel we will now agree to the fact that I will write TFTP and drive packages via WiFi.) - mikelsv
    • @mikelsv God help. The protocol is really simple (although at the expense of speed - for each packet - a ticket), and WiFi, as I understand it, works reliably, so it’s not for long. - alexlz