1. 首先需要下载cppzmq的库
github:https://github.com/zeromq/cppzmq
2. 将zmq.hpp 和 zmq_addon.hpp 两个库文件放入到自己的工程里面
3. 写demo
/*server.cpp*/
#include <iostream>
#include <unistd.h>
#include "zmq.hpp"
#include "zmq_addon.hpp"
int main()
{
zmq::message_t msg;
zmq::context_t zmq_context(1); //获取zmq上下文
zmq::socket_t zmq_socket(zmq_context,ZMQ_PUB); //创建ZMQ_PUB模式的socket
zmq_socket.bind("tcp://*:6666"); //绑定端口号
std::string send_str = "hello world!";
msg.rebuild(send_str.data(), send_str.size());
while(1)
{
zmq_socket.send(msg, zmq::send_flags::dontwait);
sleep(1);
}
return 0;
}
/*client.cpp*/
#include <iostream>
#include <string>
#include "zmq.hpp"
#include "zmq_addon.hpp"
int main()
{
zmq::context_t zmq_context(1); //获取zmq上下文
zmq::socket_t zmq_socket(zmq_context,ZMQ_SUB); //创建ZMQ_PUB模式的socket
zmq_socket.connect("tcp://localhost:6666"); //通过一个socket创建一个对外连接
char topic[] = "333";
sock.set(zmq::sockopt::subscribe, zmq::const_buffer(topic, strlen(topic))); //设置过滤条件
zmq::message_t msg;
while(1)
{
sock.recv(msg, zmq::recv_flags::none); //接收消息
cout << msg.to_string() << endl;
}
return 0;
}
4. 编译
g++ server.cpp zmq.hpp zmq_addon.hpp -o server -lzmq
g++ client.cpp zmq.hpp zmq_addon.hpp -o client -lzmq