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

  • 相关阅读:
    .net core 3.1 添加区域 area
    JMeter 网站并发测试工具使用教程
    .net core 3.1 使用ado.net
    .net core 3.1 mvc 调试的时 更改cshtml页面 刷新浏览器不更新
    .net core 3.1 autofac(webapi / mvc 通过)
    .net core3.1 rest api 无法接收 vue 中 axios 请求
    .net core 3.1 web api 允许跨域
    mysql 中文匹配
    mysql 分组排序
    mysql json处理
  • 原文地址:https://www.cnblogs.com/yyl001/p/11213340.html
Copyright © 2011-2022 走看看