废话不多说
前文的your_tool_cli_msg.proto 文件生成 your_tool_cli_msg.pb.h/your_tool_cli_msg.pb.cc
Message.h
#ifndef YOUR_TOOL_MESSAGE_H_
#define YOUR_TOOL_MESSAGE_H_
#include <zmq.hpp>
#include <string>
#include "your_tool_cli_msg.pb.h"
using TPLPROTO = your_tool_proto::your_tool_climsg;
class Message final
{
public:
Message() = default;
~Message() = default;
void createReqMessage(const std::string& cmd,
const your_tool_proto::CliCommand_Type cliCommandType,
const your_tool_proto::Request_ReqType reqType,
const std::string& file_content,
const std::string& module,
const std::string& filename);
void createRspMessage(const your_tool_proto::CliCommand_Type cliCommandType,
const your_tool_proto::Response_Status respStatus,
const std::string& xmlData,
const std::string& errorInfo);
// Used when receives
void parseMessage(const zmq::message_t &zmsg);
zmq::message_t convert2ZmqMessage() const;
const your_tool_proto::climsg &getProtoMsg() const
{ return msg_; }
private:
your_tool_proto::climsg msg_;
};
#endif //YOUR_TOOL_MESSAGE_H_
Message.cpp
#include <google/protobuf/text_format.h>
#include <zmq.hpp>
#include <iostream>
#include "Message.h"
//请求消息组装
void Message::createReqMessage(const your_tool_proto::CliCommand_Type cliCommandType,
const your_tool_proto::Request_ReqType reqType,
const std::string& file_content,
const std::string& module,
const std::string& filename)
{
msg_.mutable_command()->set_type(cliCommandType);
msg_.mutable_request()->set_reqtype(reqType);
msg_.mutable_request()->set_file_content(file_content);
msg_.mutable_request()->set_module(module);
msg_.mutable_request()->set_filename(filename);
}
//响应消息组装
void Message::createRspMessage( const your_tool_proto::CliCommand_Type cliCommandType,
const your_tool_proto::Response_Status respStatus,
const std::string& xmlData,
const std::string& errorInfo)
{
msg_.mutable_command()->set_type(cliCommandType);
msg_.mutable_response()->set_status(respStatus);
msg_.mutable_response()->set_xmldata(xmlData);
msg_.mutable_response()->set_errorinfo(errorInfo);
}
//序列化这里很好用
zmq::message_t Message::convert2ZmqMessage() const
{
zmq::message_t zmqmsg(msg_.ByteSizeLong());
msg_.SerializeToArray(zmqmsg.data(), zmqmsg.size());
return zmqmsg;
}
// parse也好用
void Message::parseMessage(const zmq::message_t &zmsg)
{
if (!msg_.ParseFromArray(zmsg.data(), zmsg.size()))
{
std::cout <<"MSG parse failed, size="<< zmsg.size()<<std::endl;
};
}