簡體   English   中英

如何在 C/C++ 中通過 TCP 發送.mp4 文件?

[英]How to send .mp4 file over TCP in C/C++?

我正在嘗試通過 C++ 應用程序中的 TCP 客戶端/服務器發送文件。 場景非常簡單; 客戶端發送文件和服務器端接收文件。 我可以成功發送基於文本(如.cpp 或.txt)的文件,但是當我嘗試發送.mp4 或.zip 等文件時,服務器上收到的文件已損壞。

客戶端.cpp

FILE *fptr = fopen(m_fileName.c_str(), "rb");

off_t offset = 0;
int bytes = 1;
if(fptr){
    while (bytes > 0){
        bytes = sendfile(m_sock, fptr->_fileno, &offset, BUFFER_SIZE);
        std::cout<< "sended bytes : "<< offset << '\n';
    }
}

fclose(fptr);
std::cout<< "File transfer completed!\n";

服務器.cpp

//some stuff...
for (;;) {
    if ((m_result = recv(epes[i].data.fd, buf, BUFFER_SIZE, 0)) == -1) {
        if (errno == EAGAIN)
            break;
        exit_sys("recv");
    }
    
    if (m_result > 0) {
        buf[m_result] = '\0';
        
        std::ofstream outfile;
        if(!outfile.is_open())
            outfile.open(m_filename.c_str(), std::ios_base::app | std::ios_base::binary);
        
        outfile << std::unitbuf << buf;
        m_filesize -= m_result;

        std::cout << "count       : " << m_result << '\n';
        std::cout << "remain data : " << m_filesize << '\n';

        if(!m_filesize){
            outfile.close();
            m_fileTransferReady = 0;
            std::cout<<"File transfer stop\n";
            if (send(epes[i].data.fd, "transferok", 10, 0) == -1)
                exit_sys("send");
        }
    }
    //some stuff for else
}

我在發送和接收文件時使用了二進制模式,但我想這還不夠。 格式化文件有特殊的發送方法嗎?

我按照 GM 在評論中提到的方式找到了解決方案。 將 null 字符添加到以二進制模式打開的文件的末尾會導致非基於文本的文件出現問題。 另一個問題是使用 << 運算符。 而不是stream的寫成員function需要使用。 因此;

服務器.cpp

//...
//...
    
    if (m_result > 0) {
        //buf[m_result] = '\0';       //Deleted!
        std::ofstream outfile;
        if(!outfile.is_open())
            outfile.open(m_filename.c_str(), std::ios_base::app | std::ios_base::binary);
        
        outfile << std::unitbuf;      //Modified
        outfile.write(buf, m_result); //Added
        m_filesize -= m_result;
        
        //...
        //...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM