标签:
之前也有提到 使用订阅发布 pub sub模式必须要显示定义ZMQ_SUBSCRIBE
只有以此模式定义的过滤字节开头的消息才会被订阅者收到
如果想收到所有信息
可定义subscriber.setsockopt(ZMQ_SUBSCRIBE, "", 0); 此类过滤器
示例很简单 我将示例代码发布者与订阅者整合到一个工程中 开启两个线程演示
上代码
// psenvpubsub.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include "zhelpers.hpp" #include <thread> void PubFunc() { zmq::context_t context(1); zmq::socket_t publisher(context, ZMQ_PUB); publisher.bind("tcp://*:5563"); while (1) { // Write two messages, each with an envelope and content s_sendmore(publisher, "A"); s_send(publisher, "We don‘t want to see this"); s_sendmore(publisher, "B"); s_send(publisher, "We would like to see this"); Sleep(1000); } return; } void SubFunc() { zmq::context_t context(1); zmq::socket_t subscriber(context, ZMQ_SUB); subscriber.connect("tcp://localhost:5563"); subscriber.setsockopt(ZMQ_SUBSCRIBE, "B", 1); while (1) { // Read envelope with address std::string address = s_recv(subscriber); // Read message contents std::string contents = s_recv(subscriber); std::cout << "[" << address << "] " << contents << std::endl; } } int main() { //开启两个线程 一个发 一个收 // 用于演示发布者的封包发送及订阅者的过滤使用 std::thread threadPub = std::thread(PubFunc); std::thread threadSub = std::thread(SubFunc); threadPub.join(); threadSub.join(); return 0; }
标签:
原文地址:http://www.cnblogs.com/itdef/p/5349782.html