使用 ZMQ 和 protobuf 时接收 0 大小的消息 [英] Receiving 0 size messages while using ZMQ and protobuf
问题描述
我正在尝试使用 ZMQ 在客户端和服务器之间建立一个基本的通信系统.我使用 protobuf 作为消息格式.我的问题是当我从客户端发送消息时,消息大小为 34,但服务器上收到的消息大小为 0.
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.
以下是我的代码;
客户端.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;
服务器.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();
客户端的输出是:
Size of message string is 34
服务器的输出是:
Size of message received is 0
我也尝试过切换到 ParseToArray,但没有帮助.任何形式的帮助表示赞赏.
I have tried tried switching to ParseToArray also but it did not help. Any kind of help is appreciated.
推荐答案
我已经用另一种方式解决了.其实之前我安装了 libzmq lib ,但后来当我切换到 libzmq3-dev 时,它对我有用.
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.
这篇关于使用 ZMQ 和 protobuf 时接收 0 大小的消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!