简体   繁体   English

使用C ++ Client通过Zmq发送JSON对象-Python服务器

[英]Send JSON Object through Zmq with C++ Client - Python Server

i'm trying to exchange a Json object through a c++ client and a python server using zeromq. 我正在尝试通过C ++客户端和使用zeromq的python服务器交换Json对象。

server.py 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)

client.cpp client.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();
     }

executing those programs, in the server.py this error accours: 执行这些程序,在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'

I'm using jsoncpp for Json in c++. 我在C ++中将jsoncpp用于Json。

How can I exchange a Json message between C++ and Python? 如何在C ++和Python之间交换Json消息?

You are trying to convert the json string to a python object twice. 您尝试两次将json字符串转换为python对象。 Both the following lines return objects, not strings. 以下两行都返回对象,而不是字符串。

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

Either receive the data with socket.recv_json() and remove the line after it, or receive the data with socket.recv() and then load the string in json_str into a python object with json.loads(json_str) . 使用socket.recv_json()接收数据并删除其后的行,或者使用socket.recv()接收数据,然后使用json.loads(json_str)的字符串json_str到python对象中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM