Skip to content

Instantly share code, notes, and snippets.

@ShaneTsui
Created July 3, 2020 01:08
Show Gist options
  • Save ShaneTsui/e6c73f41f9f460b7ceaad274376b3f3f to your computer and use it in GitHub Desktop.
Save ShaneTsui/e6c73f41f9f460b7ceaad274376b3f3f to your computer and use it in GitHub Desktop.
Communicate using json string with ZMQ
#include <zmq.hpp>
#include <string>
#include <iostream>
#include "json.hpp"
int main() {
zmq::context_t context;
zmq::socket_t socket(context, ZMQ_REQ);
socket.connect("tcp://localhost:5555");
for (int i = 0; i < 10; ++i) {
nlohmann::json request;
request["a"] = 123;
std::string json_str = request.dump();
zmq::message_t query(json_str.length());
memcpy(query.data(), (json_str.c_str()), (json_str.size()));
socket.send(query);
zmq::message_t reply;
socket.recv(reply);
auto reply_str = std::string(static_cast<char *>(reply.data()), reply.size());
std::cout << reply_str << std::endl;
auto reply_json = nlohmann::json::parse(reply_str);
std::cout << reply_json["a"] << " " << int(reply_json["a"]) << std::endl;
}
}
import zmq
import time
context = zmq.Context()
socket = context.socket(zmq.REP)
socket.bind("tcp://0.0.0.0:5555")
while True:
# Wait for next request from client
message = socket.recv_json()
print("Received request: ", message)
time.sleep(1)
ret = {"a": 123, "b": 321}
socket.send_json(ret)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment