C++ wxsocket TCP 服务器发送无符号字符数组,但 python 客户端再获得 4 个字节
C++ wxsocket TCP server send unsigned char array but python client get 4 more bytes in
嗨,我使用 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 或控制台所在的任何语言环境的转换。
如果您可以得到它并发布该信息,它可能会帮助其他人帮助您。
- 我可以与 python 服务器而不是 c++ 客户端建立 tcp/ip 套接字吗?
- C++套接字客户端到 Python 服务器未创建连接
- Freeopcua C++ 客户端和 Python Opcua 的组合会在 getChild() 上抛出错误
- 将 QImage 从 c++ 客户端发送到 python 服务器
- 服务器 Python 客户端 C++ 10061
- 有没有办法用c ++ Gsoap客户端调用python soap spyne服务器?
- 使用套接字从 Python(客户端)发送到 C++(服务器)数组的数据
- Qt C++ 带有 Python 客户端的 SSL/TLS 服务器
- 如何将数据序列化为C++ zmq 客户端和 Python zmq 服务器之间的通信
- 如何使用 Python 实验室机器作为我的C++客户端代码的服务器
- 使用C++客户端 - Python 服务器通过 Zmq 发送 JSON 对象
- 为什么一旦ZeroMQ C++客户端针对python服务器运行,"stack smashing detected"?
- 简单 Python 客户端和C++服务器的示例
- 如何将套接字与 Python 客户端和C++服务器一起使用
- Python和C语言的服务器和客户端
- 如何将JPEG帧从Java客户端流式传输到Python服务器
- 将char数组从c++(客户端)传递到python(服务器)winsock
- Qt/C++echo客户端+python echo服务器存在问题(未收到数据)
- Zeromq:如何从python客户端向c++服务器发送超过30个字符的消息
- RPC c++服务器和Python客户端