python - 从 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()
解决方案
1)您将向量的地址写入套接字似乎很奇怪。
我认为发送应该是这样的:
send(new_socket, imageDataVec.data()...);
2)据我了解,在客户端,您正在尝试读取 8 字节长度的整数。但我看不到服务器将这些数据写入何处。
3) 使用 int64_t 而不是 long 类型,因为您无法确定 long 大小。
推荐阅读
- r - R替换跨数据框的许多列中的特定值
- powershell - 使用 Wsusscn2.cab 离线包检测旧补丁,但服务器是最新的
- python - Pandas 在使用 pd.reset_option('all') 时向我发送警告
- javascript - 任何人都可以帮助我用 Javascript 编写到 C# 的排序功能或解释我这些代码行是如何工作的
- python - 根据 A 列的范围修改 B 列的值
- caching - Apollo 客户端从缓存中驱逐但从不重新渲染
- android - SurfaceView 的生命周期
- python - sympy plot_implicit 中的 get_points
- php - current() 期望参数 1 是数组,在
- javascript - 在几个小时内改变背景