2016-06-11 2 views
1

저는 zonomq를 사용하여 C++ 클라이언트와 Python 서버를 통해 Json 객체를 교환하려고합니다.Zmq를 통해 JSON 객체를 C++ 클라이언트에서 전송 - Python 서버

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

 #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에, 그 프로그램을 실행이 오류 accours : I가 jsoncpp을 사용하고

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.

C++과 Python간에 Json 메시지를 어떻게 교환 할 수 있습니까?

답변

0

json 문자열을 python 개체로 두 번 변환하려고합니다. 다음 줄은 모두 문자열이 아닌 객체를 반환합니다.

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

socket.recv_json()으로 데이터를 수신하고, 그 후, 광고를 제거하거나 socket.recv()으로 데이터를 수신 한 다음에 json.loads(json_str) 파이썬 객체로 json_str 문자열을로드 어느.

+0

감사합니다. 이러한 솔루션이 작동합니다! –

+0

거기에'socket.recv_json()'에 대한 C++ 메소드가 있습니까? –

+0

나는 거기 있다고 믿지 않는다. 이 페이지 http://api.zeromq.org/2-1:zmq-cpp에는 api의 약간 오래된 버전이 나와 있지만 json을 직접 다루는 소켓 객체에는 어떤 메소드도없는 것 같습니다. – user2027202827

관련 문제