I am trying to set up a basic communication system between client and server using ZMQ. I am using protobuf for the message format. My problem is when I send the message from client the message size is 34 but the message size received on the server is 0.
Following is my code;
Client.cpp
tutorial::Person person;
person.set_id(1234);
person.set_name("john");
person.set_email("john@mxyz.com");
person.set_phonenumber("12345678");
zmq::context_t context (1); // Prepare our context and socket
zmq::socket_t socket (context, ZMQ_PAIR);
std::cout << "Connecting to server…" << std::endl;
int linger = 0;// ms
socket.setsockopt(ZMQ_LINGER, &linger, sizeof(linger));
socket.connect ("tcp://127.0.0.1:20000");
std::string msg_str;
person.SerializeToString(&msg_str);
std::cout << "Size of message string is "<< msg_str.size()<<std::endl;
zmq::message_t request (msg_str.size());
memcpy ((void *) request.data (), msg_str.c_str(), msg_str.size());
std::cout << "Sending Person data ..." << std::endl;
socket.send (request);
socket.close();
google::protobuf::ShutdownProtobufLibrary();
return 0;
Server.cpp :
zmq::context_t context(1); // Prepare our context and socket
zmq::socket_t socket(context, ZMQ_PAIR);
int linger = 0; // ms
socket.setsockopt(ZMQ_LINGER, &linger, sizeof(linger));
socket.bind("tcp://127.0.0.1:20000");
while (true)
{
zmq::message_t request;
int recieved = socket.recv(&request);
std::string msg(static_cast<char*>(request.data()),request.size());
std::cout<<"Size of message recieved is "<< msg.size()<<std::endl;
tutorial::Person person;
person.ParseFromString(msg);
std::string text_str1;
google::protobuf::TextFormat::PrintToString(person, &text_str1);
}
socket.close();
Output of Client is :
Size of message string is 34
Output of server is :
Size of message received is 0
I have tried tried switching to ParseToArray also but it did not help. Any kind of help is appreciated.
I have solved it with another way. Actually earlier I installed libzmq lib , but later when I switched to libzmq3-dev it worked for me.
I had the exact same problem; what I found is that the
zmq::message_t
had to go out of scope ORrebuild
needed to be called.For example, if the publisher looked like this.
The subscriber would receive messages of zero length. If the code was changed to
OR
Then the subscriber would receive a 3-byte message.