• NetMQ使用——发布订阅模式 Publisher-Subscriber


    发布者

            readonly static ManualResetEvent _terminateEvent = new ManualResetEvent(false);
            /// <summary>
            /// NetMQ 发布端
            /// </summary>
            public static void Start()
            {
                string[] weathers = new string[6] { "晴朗", "多云", "阴天", "", "", "" };
    
                Console.WriteLine("发布多个地区天气预报:");
    
                using (var pub = new PublisherSocket())
                {
                    pub.Connect("tcp://127.0.0.1:55555");
    
                        var rng = new Random();
                        string msg;
                        int sleeptime = 1000;//1秒
    
                        ///指定发布的时间间隔,1秒
                        while (_terminateEvent.WaitOne(1000) == false)
                        {
                            //随机生成天气数据
                            int zipcode = rng.Next(0, 99);
                            int temperature = rng.Next(-50, 50);
                            int weatherId = rng.Next(0, 5);
                        msg = string.Format("{0} {1} {2}", zipcode, temperature, weathers[weatherId]);
                        //pub.SendMoreFrame(weathers[weatherId]).SendFrame(msg);
    
                        pub.SendFrame(msg);
    
                        Console.WriteLine(msg);
                            Thread.Sleep(sleeptime);
                        }
                 
                }
            }

    订阅者:

      using (var sub = new SubscriberSocket())
                    {
                        sub.Options.ReceiveHighWatermark = 1000;
                        sub.Connect("tcp://127.0.0.1:12345");
                        //sub.Subscribe("晴朗");//空字符串表示订阅所有,仅订阅“AAA”:sub.Subscribe("AAA");这时第一次ReceiveString()将返回“AAA”,之后才是真正的消息。
                        sub.Subscribe("");
                        while (true)
                        {
                            string results = sub.ReceiveFrameString();
                            //sub.SendFrame(results);
                            Console.WriteLine(results);
    
                        }
                    }

    注意:订阅者必须选使用           sub.Subscribe("");

    使用多个订阅者要更改连接方式

        using (var pub = new PublisherSocket("@tcp://127.0.0.1:12345"))

      using (var sub = new SubscriberSocket(">tcp://127.0.0.1:12345"))

  • 相关阅读:
    Python pip 下载速度慢? Windows 设置 国内源,用阿里云国内镜像加速
    Go timer 是如何被调度的?
    Go sync.Pool 浅析
    一次错误使用 go-cache 导致出现的线上问题
    golang面向对象分析
    一文完全掌握 Go math/rand
    这一次,彻底搞懂 Go Cond
    面试题:让你捉摸不透的 Go reslice
    当 Go struct 遇上 Mutex
    这可能是最容易理解的 Go Mutex 源码剖析
  • 原文地址:https://www.cnblogs.com/yyl001/p/11213340.html
Copyright © 2020-2023  润新知