目标:
我正在编写一个套接字服务器/客户端程序(c++是服务器,python是客户端)来发送携带数据的xml字符串。我的目标是能够通过套接字从 Python 中的 C++ 接收 xml 消息。
方法
VS2013专业版 通过 Vizard 4.1 的 Python 2.7.2
1) 套接字通信创建得很好,没有问题。我可以发送/接收东西
2) 通信初始化后,c++开始使用Cmarkup创建xml对象
3)c++将xml对象转换为std::string类型
4) C++ 通过流将 std::string 发送到 Python
问题:
Python 中从 C++ 接收到的“字符串”被解释为垃圾符号(不是想冒犯,有人可能对它们有强烈的感情,我没有;)如果你打开一个记事本,它们看起来就像你在记事本中看到的符号。二进制文件。这并不奇怪,因为通过流发送的数据是二进制的。
我不明白的是如何让 Python 理解流。
尝试修复失败:
1) 确保VS2013项目使用Unicode字符
2) 尝试将流转换为 python 字符串并对其进行解码 string.decode()
3) 尝试使用 Unicode()
4) 还尝试使用 binascii() 方法来获得一些有用的、小的改进,但仍然与我从 c++ 发送的字符不同
如果有人能提供一些关于为什么会发生这种情况的见解,我将不胜感激。我读过几个关于通过套接字发送数据的方式的论坛,但在我看来,编码和解码的这方面仍然是垃圾邮件-鲭鱼-砂锅。
这是创建 xml、转换为字符串然后发送的服务器代码
MCD_CSTR rootname("ROOT");//initializes name for root node
MCD_CSTR Framename("FRAME");//creates name for child node
CMarkup xml;//initializes xml object using Cmarkup method
xml.AddElem(rootname);//create the root node
xml.IntoElem();//move into it
xml.AddElem(Framename, MyClient.GetFrameNumber().FrameNumber);//create child node with data from elsewhere, FrameNumber is an int
CStringA strXML = xml.GetDoc();//convert the xml object to a string using Cmarkup method
std::string test(strXML);//convert the CstringA to a std::string type
std::cout << test << '\n';//verify that the xml as a string looks right
std::cout << typeid(test).name() << '\n';//make sure it is the right type
iSendResult = send(ClientSocket, (char *)&test, sizeof(test), 0);//send the string to the client
以下是在 Python 中接收 xml 字符串的代码:
while 1:
data = s.recv(1024)#receive the stream with larger than required buffer
print(data)#see what is in there
if not data: break#if no data then stop listening for more
最佳答案
由于 test
是一个字符串,因此这不起作用:
iSendResult = send(ClientSocket, (char *)&test, sizeof(test), 0);//发送字符串
std::string
不是字符数组。它是一个对象,该行所做的就是向套接字发送无意义的字节。您想要发送数据,而不是对象。
iSendResult = send(ClientSocket, (char *)test.c_str(), test.length(), 0);//发送字符串
关于python 无法理解通过 Winsock 发送的 C++ 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27925986/