• zeromq学习记录(七)订阅发布消息封装


    之前也有提到 使用订阅发布 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;
    }
    View Code

  • 相关阅读:
    Git中tag标签的使用
    antd vue Layout 组件收缩展开自定义
    antd vue Popover气泡卡片的使用
    antd vue Tree树形控件的使用
    antd vue Message 全局提示的使用
    tp5.1 关联条件查询haswhere 用field限制字段失效的问题
    Chrome 调试技巧: 调整网速
    html2canvas导出图片模糊
    点击其他区域不让编辑器失去焦点
    启动的项目经常挂怎么办
  • 原文地址:https://www.cnblogs.com/itdef/p/5349782.html
Copyright © 2020-2023  润新知