C++ wxsocket TCP 服务器发送无符号字符数组,但 python 客户端再获得 4 个字节

C++ wxsocket TCP server send unsigned char array but python client get 4 more bytes in

本文关键字:客户端 python 字节 服务器 TCP wxsocket 数组 字符 无符号 C++      更新时间:2023-10-16

嗨,我使用 TCP 套接字向 python TCP 客户端发送了一个 wxImage C++如下所示:

C++ TCP 服务器是这样的:

//this part is the TCP server m_sock send the unsigned char* ImageData
std::stringstream imageStream1;
imageStream1 << ImageData;
m_sock->Write(imageStream1.str().c_str(), imageStream1.str().length());
//Then I send a simple string "hello"
std::stringstream dataStream2;
dataStream2 <<  "hello";
m_sock->Write(dataStream2.str().c_str(), dataStream2.str().length());
dataStream2.clear();

所以我在python中收到两条消息

// This is used to receive the image data with the exact same bytes of the ImageData
packet = socket.recv(ImageDataSize)
myWxImage.SetData(packet)
// This is used to receive the second "hello" message
packet = socket.recv(1000)

我可以成功接收图像。但是当我打印消息时,它显示"****hello"而不是"hello"。它前面还有一个额外的 4 字节字符串。四个"*"是Python无法打印出来的。这是什么?我可以摆脱它吗?

std::stringstream imageStream1;
imageStream1 << ImageData;
m_sock->Write(imageStream1.str().c_str(), imageStream1.str().length());

看起来是个坏主意。我不知道 ImageData 的类型,但将其转换为std::stringstream绝对不是最好的方法。如果ImageData只包含对原始图像缓冲区的引用,请使用该缓冲区。图像不是字符串,显然,如果您从数据中可能包含x00的东西中获取c_str(),事情就会出错(因为这通常是终止 C 字符串的原因)。

然后:

//Then I send a simple string "hello"
std::stringstream dataStream2;
dataStream2 <<  "hello";
m_sock->Write(dataStream2.str().c_str(), dataStream2.str().length());
dataStream2.clear();

嗯,你明白你在这里写的是什么吗?你拿一个完全有效的C字符串,"hello",你把它推到一个字符串流上,只是为了再次得到一个C字符串?

老实说:我认为您正在从示例中复制和粘贴代码而不理解它。在使用之前,您应该返回并了解每一行。

如何删除"****"

通常,要从python字符串中删除字符,您可以这样做:

cleaned_data = str(packet).replace("*", "")

请记住,当您以packet接收数据时,您接收的是字节而不是字符串,因此,如果您尝试直接打印,python会为您进行隐式转换。在这种情况下,我认为最好进行显式转换并删除开头。

但是,它并不能解决为什么首先获得角色的问题。这 4 个"*"可能源于编码问题。

故障排除

将 python 程序连接到调试器(可能是 PyCharm)是值得的,这样您就可以看到"Hello"之前的实际值,这将使您了解查找的位置,这样您就不必处理从字节到 unicode 或控制台所在的任何语言环境的转换。

如果您可以得到它并发布该信息,它可能会帮助其他人帮助您。