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"))

posted @ 2019-07-19 15:54  乌柒柒  阅读(908)  评论(0编辑  收藏  举报