void TCPClient::DownloadFile(string fileName) { auto file = new fstream(); OpenFile(file, GetLocalFileName(fileName)); fpos_t currentProgress = file->tellp(); fpos_t fileSize = 0; auto done = false; cout << "Download started." << endl; while (!done) { try { SendMessage(this->_tcp_socket, CreateFileInfo(fileName, currentProgress)); fileSize = ReceiveFileSize(); ReceiveFile(file, currentProgress, fileSize); done = true; } catch (ConnectionInterrupted e) { currentProgress = e.GetProgress(); Reconnect(); } catch (ServerError) { file->close(); throw; } catch (runtime_error e) { cout << e.what() << endl; Reconnect(); } } file->close(); cout << "Done." << endl; }
fpos_t UDPClient::ConnectToServer() { ///auto connectionInfo = new char[BUFFER_SIZE]; auto infoSize = CreateConnectionInfo(buffer, BUFFER_SIZE); while(true) { try { SendRawDataTo(this->_udp_socket, buffer, infoSize, serverAddressInfo); auto fileSize = ReceiveFileSize(); return fileSize; } catch(ServerError e) { throw; }catch(runtime_error e) { cout << e.what() << endl; Sleep(1000); } } }
int Preparation(int socket) { int fileSize; char fileSizeStr[64] = {0}; char fileName[256] = {0}; FILE *wrfile; ConnectionInfo connectionInfo; if (ReceiveFileName(socket, fileName) < 1) { return -1; } send(socket, fileName, 1, 0); if (ReceiveFileSize(socket, fileSizeStr) < 1) { return -1; } send(socket, fileName, 1, 0); fileSize = atoi(fileSizeStr); printf("Receiving %s file, %s bytes...\n", fileName, fileSizeStr); wrfile = fopen(fileName, "w+"); if (wrfile == NULL) { puts ("Error while opening file."); return -1; } connectionInfo.socket = socket; connectionInfo.wrfile = wrfile; connectionInfo.fileSize = fileSize; connectionInfo.totalBytesRead = 0; AddInfo (&info, connectionInfo); return 1; }