zoukankan      html  css  js  c++  java
  • 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"))

  • 相关阅读:
    优先队列
    Problem W UVA 662 二十三 Fast Food
    UVA 607 二十二 Scheduling Lectures
    UVA 590 二十一 Always on the run
    UVA 442 二十 Matrix Chain Multiplication
    UVA 437 十九 The Tower of Babylon
    UVA 10254 十八 The Priest Mathematician
    UVA 10453 十七 Make Palindrome
    UVA 10163 十六 Storage Keepers
    UVA 1252 十五 Twenty Questions
  • 原文地址:https://www.cnblogs.com/yyl001/p/11213340.html
Copyright © 2011-2022 走看看