通过socket cpp发送文件

时间:2017-08-24 08:40:57

标签: c++ sockets

您好我正在尝试通过套接字从服务器向客户端发送文件,然后在客户端上打开它们。我的问题是我可以毫无问题地发送图片和文档,但是当我尝试发送视频时,到达目的地的数据已损坏。目标文件与源文件的大小相同。

服务器

int Server::data_trans_send(Client *client, const char *filename, const char *loc){
    int re;
    //client object stores socket ID
#ifdef _WIN32
    SOCKET dest = (client->socketfd());
#else
    int dest = (client->socketfd());
#endif
    string sloc;
    int resp = 0;
    sloc.append (loc);
    sloc.append (filename);
    //opens a file in binary
    FilePrep file(sloc.c_str ());
    long int filesize = file.filesize();
    //reads binary data into a char array
    char *data = file.preptdata();
    //sends the filesize
    re = send(dest, &filesize, sizeof(long int), 0);
    if(re < 0){return -1;}
    re = 0;
    re = recv (dest, &resp, sizeof(int), 0);
    if(re < 0){return -2;}
    re = 0;
    //sends the filename
    re = write(dest, filename, strlen(filename));
    if(re < 0){return -3;}
    re = 0;
    re = recv (dest, &resp, sizeof(int), 0);
    if(re < 0){return -4;}
    re = 0;
    //sends the filedata
    re = write(dest, data, filesize);
    if(re < 0){return -5;}
    re = 0;
    re = recv (dest, &resp, sizeof(int), 0);
    if(re < 0){return -6;}
    re = 0;
    return 1;
}

客户端

int Client::data_trans_recv(const char *loc){
    //server socket ID is stored in the private section of class
    long int filesize = 0;
    int re;
    int resp = 1;
    char *filename = new char[64];
    //recieves the filesize 
    re = recv(*sockfd, &filesize, sizeof(long int), 0);
    if(re < 0){return -1;}
    re = 0;
    re = send(*sockfd, &resp, sizeof(int), 0);
    if(re < 0){return -2;}
    re = 0;
    //recieves the filename 
    re = read(*sockfd, filename, 64);
    if(re < 0){return -3;}
    re = 0;
    re = send(*sockfd, &resp, sizeof(int), 0);
    if(re < 0){return -4;}
    re = 0;
    save_filename (filename);
    //creates an empty file and opens it in binary
    BuildData file(filesize);
    //returns ptr to array to write data to file
    char *dest = file.fileptr();
    //recieves the filedata 
    re = read(*sockfd, dest, filesize);
    if(re < 0){return -5;}
    re = 0;
    re = send(*sockfd, &resp, sizeof(int), 0);
    if(re < 0){return -6;}
    re = 0;
    string floc;
    floc.append (loc);
    floc.append (filename);
    //writes array to file
    file.writeData(floc.c_str (), dest);
    delete filename;
    return 1;
}

使用1整数的Send和recv只是为了同步这两个函数。

构建数据

#include "BuildData.h"
#include <iostream>
#include <fstream>
using namespace std;

BuildData::BuildData(long int file_size) {
    data = new char[file_size];
    filesize = file_size;
}

BuildData::~BuildData() {
    delete data;
    file.close();
}

int BuildData::writeData(const char *loc, char *bits){
    file.open(loc, ios::out | ios::binary | ios::trunc);
    if(file.is_open()){
        file.write(bits, filesize);
        return 1;
    }
    return -1;
}

char *BuildData::fileptr(){return data;}

0 个答案:

没有答案