簡體   English   中英

.CORE 5 Web Api 和客戶端MQTT

[英].CORE 5 Web Api and Client MQTT

是否可以創建 a.core webapi 項目和 mqtt 客戶端? 例如,在 startup.cs 中創建一個單獨的線程,您可以在其中實例化一個 mqtt 客戶端

我嘗試添加一個 Singleton 服務來在 startup.cs 中實例化 mqtt 客戶端,它工作正常,程序接收主題上發布的消息。 第一個問題,在這個位置創建這個服務是否正確?

問題是當我嘗試使用 package 控制台工具添加數據庫的遷移或更新時。 該命令未完成排序並且控制台被鎖定。

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer("name=ConnectionStrings:DefaultConnection"));
            services.AddSingleton<MyMqtt>(new MyMqtt());
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "CoWorkOfficeWebApi", Version = "v1" });
            });
        }

Class

    public class MyMqtt
    {
        MqttClient client;

        public MyMqtt()
        {
            // create client instance 
            client = new MqttClient("127.0.0.1");
            // register to message received 
            client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
            string clientId = Guid.NewGuid().ToString();
            client.Connect(clientId);
            // subscribe to the topic "/home/temperature" with QoS 2 
            client.Subscribe(new string[] { "/home/temperature" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
        }


        static void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
        {
            string msg = Encoding.UTF8.GetString(e.Message);
            Console.WriteLine($"Topic: {e.Topic}, Message: {msg}");
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM