【问题标题】:Send JSON Object through Zmq with C++ Client - Python Server使用 C++ 客户端通过 Zmq 发送 JSON 对象 - Python 服务器
【发布时间】:2016-06-12 00:18:25
【问题描述】:

我正在尝试通过 c++ 客户端和使用 zeromq 的 python 服务器交换 Json 对象。

server.py

 import zmq
 import json

 context = zmq.Context()
 socket = context.socket(zmq.REP)
 socket.bind("tcp://*:5555")

 while True:
     json_str = socket.recv_json()
     data_print = json.loads(json_str)
     Type = data_print['Type']
     Parameter = data_print['Parameter']
     Value = data_print['Value']
     print(Type,Parameter,Value)

客户端.cpp

     #include <zmq.hpp> 
     #include <string>
     #include <iostream>
     #include <sstream>
     #include <json/json.h>
     #include <typeinfo>

     class multi_usrp_emulation{
     public:
        void client1(){

            std::string strJson="{\"Type\":\"TX\", \
                                  \"Parameter\" : \"Frequency\" ,\
                                  \"Value\" : \"5.17e9\" \
                                 }";

            Json::Value root;
            Json::Reader reader;
            reader.parse(strJson.c_str(),root);
            Json::FastWriter fastwriter;
            std::string message = fastwriter.write(root);
            zmq::context_t context (1);
            zmq::socket_t socket (context, ZMQ_REQ);
            socket.connect ("tcp://localhost:5555");
            zmq::message_t request (message.size());
            memcpy (request.data (), (message.c_str()), (message.size()));
            socket.send(request);
           }
     };
     int main (void)
     {

        multi_usrp_emulation caller;
        caller.client1();
     }

执行这些程序,在 server.py 中出现此错误:

data_print = json.loads(json_str)
File "/usr/lib/python3.4/json/__init__.py", line 312, in loads
   s.__class__.__name__))
TypeError: the JSON object must be str, not 'dict'

我在 C++ 中为 Json 使用 jsoncpp。

如何在 C++ 和 Python 之间交换 Json 消息?

【问题讨论】:

    标签: python c++ json zeromq


    【解决方案1】:

    您正在尝试将 json 字符串转换为 python 对象两次。以下两行都返回对象,而不是字符串。

    json_str = socket.recv_json()
    data_print = json.loads(json_str)
    

    要么用socket.recv_json()接收数据并删除它后面的行,要么用socket.recv()接收数据,然后用json.loads(json_str)json_str中的字符串加载到python对象中。

    【讨论】:

    • socket.recv_json()有c++方法吗?
    • 我不相信有。这个页面api.zeromq.org/2-1:zmq-cpp记录了一个稍微旧的api版本,但是socket对象上似乎没有任何方法可以直接处理json。
    猜你喜欢
    • 2013-11-16
    • 2019-01-01
    • 2023-04-02
    • 2012-04-30
    • 1970-01-01
    • 2014-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多