我认为我的问题是,每次调用该函数时,都会生成新的MQTT客户端。但是我不知道该如何解决。我尝试在调用“发布”任务时连接客户端,但随后应用崩溃。 如果将发布部件放在连接功能后面,则消息将被发布。 我只是不知道如何管理每次我调用该函数时都不被迫生成新的var MQTTclient。 我可能正在监督某些事情,因为我是C#的新手,并且从未使用过此库。
namespace InfiniLight
{
public class MQTT
{
public static async Task<bool> Publish(string channel, string value)
{
var factory = new MqttFactory();
var mqttClient = factory.CreateMqttClient();
if (mqttClient.IsConnected == false)
{
Debug.WriteLine("publishing failed");
return false;
}
var message = new MqttApplicationMessageBuilder()
.WithTopic(channel)
.WithPayload(value)
.WithExactlyOnceQoS()
.WithRetainFlag()
.Build();
await mqttClient.PublishAsync(message);
return true;
}
//connect to mqtt
public static async Task Connect()
{
var factory = new MqttFactory();
var mqttClient = factory.CreateMqttClient();
string clientId = Guid.NewGuid().ToString();
string mqttURI = Preferences.Get("broker_ip", "");
string mqttUser = Preferences.Get("client_username", "");
string mqttPassword = Preferences.Get("client_password", "");
int i;
i = System.Convert.ToInt32(Preferences.Get("broker_port", "1883"));
int mqttPort = i;
bool mqttSecure = false;
var messageBuilder = new MqttClientOptionsBuilder()
.WithClientId(clientId)
.WithCredentials(mqttUser, mqttPassword)
.WithTcpServer(mqttURI, mqttPort)
.WithCleanSession();
var options = mqttSecure
? messageBuilder
.WithTls()
.Build()
: messageBuilder
.Build();
Debug.WriteLine("MQTT: connecting");
await mqttClient.ConnectAsync(options, CancellationToken.None);
Debug.WriteLine("MQTT: connected");
/*
var message = new MqttApplicationMessageBuilder()
//here it does send the message
.WithTopic("hey")
.WithPayload("I'm a mobile")
.WithExactlyOnceQoS()
.WithRetainFlag()
.Build();
await mqttClient.PublishAsync(message); */
}
}
}
答案 0 :(得分:0)
将mqttClient
更改为类的静态成员,而不是局部变量。然后,在调用Publish()
之前创建连接,或者在Publish()
中创建一次连接并使用条件检查其是否已经连接。无论哪种方式,您都可以重复使用同一对象,而不必重新创建。