首页 > 解决方案 > 从 c++ 服务器到 python 客户端接收不同大小的字节

问题描述

我正在尝试将从 C++ 服务器的文件夹中获取的一些图像发送到 Python 客户端。我已经设法将大小作为整数发送/接收,但现在我必须发送/接收实际图像。由于图像具有不同的大小,我希望客户端根据图像大小拆分字节。

我有点迷茫,因为我现在使用一个参数,例如recv(1024) ,我收到的字节比我发送的字节多得多。所以我不太确定发生了什么。

服务器

    ifstream stream(nm, std::ios::in | std::ios::binary);
if(stream.is_open())
    {


vector<char> imageDataVec((istreambuf_iterator<char>(stream)), istreambuf_iterator<char>());
cout << "Size=of=image=== " << imageDataVec.size() << " bytes";
long conv_num= htonl(imageDataVec.size());
//send(new_socket, &converted_number, sizeof(converted_number), 0);
//send(new_socket, &imageDataVec, imageDataVec.size() , 0);

//size_t sent{};
int nbytes=0;  

while (1) 
    {

    //send(new_socket, &conv_num, sizeof(conv_num), 0);
     nbytes = send(new_socket, &imageDataVec, imageDataVec.size(), 0);
//continue;
    if (nbytes <= 0) {
        std::clog << "error: while sending image\n";
        break;
}
    else
{
    //sent += nbytes;
    cout<<nbytes<<"=====1=1=1=1========"<<"bytes"<<endl;}
                       break;

    }
//fclose(fin);
}
else
{cout<<"can't open folder"<<endl;}

客户

 while(1):
    pic_bytes=s.recv(8)
    pic_bytes_amount=int.from_bytes(pic_bytes, byteorder='big', signed=False)
    print("received bytes======{}".format(pic_bytes_amount))
    f=open('pic.jpeg','wb')
    f.write(pic_bytes)
    f.close()

标签: pythonc++imagesockets

解决方案


1)您将向量的地址写入套接字似乎很奇怪。

我认为发送应该是这样的:

send(new_socket, imageDataVec.data()...);

2)据我了解,在客户端,您正在尝试读取 8 字节长度的整数。但我看不到服务器将这些数据写入何处。

3) 使用 int64_t 而不是 long 类型,因为您无法确定 long 大小。


推荐阅读