1. 安装ZMQ 框架
apt-get install libzmq3-dev
2. 或者自己build ZMQ
https://github.com/zeromq/libzmq.git
参考官网教程
3. 安装CPPZMQ
CPPZMQ 是ZMQ 的友好的C++封装,只需要一个zmq.hpp 头文件即可
git clone https://github.com/zeromq/cppzmq.git
cd cppzmq
mkdir build
cd build
cmake ..
make
sudo make install
4. 一个简单的demo
cmake_minimum_required(VERSION 3.0)
project(ZeroMQ_Client)# 设置 C++ 标准
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED True)# 查找 ZeroMQ 库
find_package(PkgConfig REQUIRED)
pkg_check_modules(ZMQ REQUIRED libzmq)find_package(cppzmq REQUIRED)
# 添加可执行文件include_directories(${cppzmq_INCLUDE_DIR}
)add_executable(client main.cpp)# 链接 ZeroMQ 库
target_link_libraries(client PUBLIC
${cppzmq_LIBRARY}
${ZMQ_LIBRARIES}
)
#include <zmq.hpp>
#include <iostream>class Client {
public:Client(const std::string& server_address) : context_(1), socket_(context_, ZMQ_REQ) {socket_.connect(server_address);std::cout << "Connected" << std::endl;}void sendCommand(const std::string& command, const std::string& model_path) {// 发送命令zmq::message_t request(command.size());memcpy(request.data(), command.c_str(), command.size());socket_.send(request);// 等待服务器响应zmq::message_t reply;socket_.recv(&reply);if (std::string(static_cast<char*>(reply.data()), reply.size()) == "pong") {// 发送模型路径zmq::message_t modelRequest(model_path.size());memcpy(modelRequest.data(), model_path.c_str(), model_path.size());socket_.send(modelRequest);// 接收服务器对模型路径的处理结果socket_.recv(&reply);if (std::string(static_cast<char*>(reply.data()), reply.size()) == "OK") {std::cout << "Model loaded successfully" << std::endl;} else {std::cout << "Failed to load model" << std::endl;}}}private:zmq::context_t context_;zmq::socket_t socket_;
};int main() {// 服务器地址std::string server_address = "tcp://127.0.0.1:2222";// 创建客户端实例Client client(server_address);// 发送命令和模型路径std::string command = "ping";std::string model_path = "cyto2torch_0";client.sendCommand(command, model_path);return 0;
}