python 无法理解通过 Winsock 发送的 C++ 字符串

标签 python c++ xml string sockets

目标:

我正在编写一个套接字服务器/客户端程序(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/

相关文章:

c++ - 等于在 C++ 中返回 false

android - 如何在android中创建侧边栏

python - 在 Scrapy 中向导出的 XML 添加属性

python - 元组由 swig 为 C++ vector 生成的 python 包装器返回

python - 在目录中查找图像序列 - 比 os.walk() 更快?

python - 为什么 tensorflow RNN 历史 + 样本预测图看起来与训练数据集如此不同?

c++ - c/c++中两个函数内容相同时,哪种风格更好?

python - 为什么我的 urls.py 不起作用?

c++ - 后期不可复制成员初始化

java - 搜索图标操作按钮未显示在操作栏中 - 无法访问搜索功能