简体   繁体   English

使用 sockets c++ 正确发送和接收二进制文件

[英]send and receive binary files properly using sockets c++

hello stackflow users,你好 stackflow 用户,

so i want to send and receive my binary file using sockets in c++ and here is how i send it from server program所以我想在 c++ 中使用 sockets 发送和接收我的二进制文件,这是我从服务器程序发送它的方式

send(Connections[conindex], reinterpret_cast<char*>(rawData), sizeof(rawData), NULL);

and here is how my client program receives it这是我的客户端程序如何接收它

char raw[647680];
recv(Connection, raw, sizeof(raw), NULL);

is there any proper way than this?还有比这更合适的方法吗? i want so that i don't have to hard code the size every time.我想要这样我就不必每次都对大小进行硬编码。 or any other alternatives etc或任何其他替代品等

A rather general way to achieve this (in both C and C++) is something like this:一种相当通用的实现方式(在 C 和 C++ 中)是这样的:

if (FILE *fp = fopen(filename, "rb"))
{
    size_t readBytes;
    char buffer[4096];
    while ((readBytes = fread(buffer, 1, sizeof(buffer), fp) > 0)
    {
        if (send(Connections[conindex], buffer, readBytes, 0) != readBytes)
        {
            handleErrors();
            break;
        }
    }
    close(Connections[conindex]);
}

And on the client side:在客户端:

if (FILE *fp = fopen(filename, "wb"))
{
    size_t readBytes;
    char buffer[4096];
    while ((readBytes = recv(socket, buffer, sizeof(buffer), 0) > 0)
    {
        if (fwrite(buffer, 1, readBytes, fp) != readBytes)
        {
            handleErrors();
            break;
        }
    }
}

Alternatives to this rather FTP-esque connection style includes sending the size of the file first, so the client will know when to stop listening instead of waiting for the disconnect.这种类似于 FTP 的连接方式的替代方案包括首先发送文件的大小,这样客户端将知道何时停止监听而不是等待断开连接。

Please note that this code is untested and merely meant to illustrate the concept.请注意,此代码未经测试,仅用于说明概念。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM