繁体   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