1
我想通過C++客戶端和使用zeromq的python服務器交換Json對象。通過zmq用C++客戶端發送JSON對象 - 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:
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'
我使用jsoncpp爲JSON在C++中。
如何在C++和Python之間交換Json消息?
謝謝,這些解決方案的工作! –
是否有一個'socket.recv_json()'的C++方法? –
我不相信。這個頁面http://api.zeromq.org/2-1:zmq-cpp記錄了api的一個稍舊的版本,但是在socket對象上似乎沒有任何方法直接處理json。 – user2027202827