可以创建mqtt项目和.core客户端吗?例如,在startup.cs中创建一个单独的线程,您可以在其中实例化一个mqtt客户端
发布于 2021-05-14 00:19:20
我尝试在startup.cs中添加一个单例服务来实例化mqtt客户端,它工作得很好,程序收到了发布的主题消息。第一个问题是,在此位置创建此服务是否正确?
问题是当我尝试使用包控制台工具添加数据库的迁移或更新时。该命令不会完成排序,并且控制台已锁定。
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" });
});
}类
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}");
}
}https://stackoverflow.com/questions/67456105
复制相似问题