我正在尝试使用Nuget包System.Net.Mqtt:我的样本Mqtt应用程序的轻量级C#... 0.3.6-pre。但是,我无法连接到我的客户端。代码如下
namespace TestMqtt
{
class MqttHelper
{
public IMqttClient client;
public async Task CreateClient()
{
MqttConfiguration configuration = new MqttConfiguration();
configuration.Port = 8883;
configuration.AllowWildcardsInTopicFilters = false;
configuration.KeepAliveSecs = 180;
string address = Dns.GetHostAddresses("hostname")[0].ToString();
client = await System.Net.Mqtt.MqttClient.CreateAsync(address, configuration);
}
public async Task Connect(MqttClientCredentials credentials)
{
await client.ConnectAsync(credentials);
}
public bool IsConnected
{
get
{
return client.IsConnected;
}
}
}
class Program
{
static void Main(string[] args)
{
try
{
MqttHelper mqttHelper = new MqttHelper();
Task.Run(() => mqttHelper.CreateClient()).Wait();
MqttClientCredentials credentials = new MqttClientCredentials("clientId", "username", "password");
Task.Run(() => mqttHelper.Connect(credentials)).Wait();
bool connected = mqttHelper.IsConnected;
}
catch (Exception ex)
{
Console.WriteLine("exception occurred {0}, press key to exit", ex.InnerException);
}
Console.ReadLine();
}
}
}
我可以使用其他客户端M2Mqtt连接相同的凭据和主机地址,所以我不确定这里有什么问题。我是异步的东西,所以我可能做错了什么,但我尽力而为,但没有成功。我得到一个例外 - Connect方法中的远程主机强行关闭现有连接。
任何帮助将不胜感激,或者如果有人使用lib连接请分享代码。 Nuget包文档没有关于如何使用库的任何细节。对C#Mqtt客户端的任何其他建议也是受欢迎的,到目前为止,我已将M2Mqtt和Net.Mqtt列入候选名单供我使用。
感谢。