Mqtt没有这样的主机已知错误

时间:2017-07-28 10:23:02

标签: c# asp.net-core mqtt

我正在.net核心应用程序中开发基于mqtt协议的应用程序我使用以下链接开发应用程序 mqtt

我的代码是

public static void Main(string[] args)
{
  MqttClient client = new MqttClient("broker.hivemq.com");
  byte code = client.Connect(Guid.NewGuid().ToString(), "username", "password");
  Console.WriteLine("code " + code);
  client.MqttMsgPublished += client_MqttMsgPublished;            
  ushort msgId = client.Publish("mytopic", // topic
     Encoding.UTF8.GetBytes("Hai this is sample chat application"), // message body
     MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, // QoS level
     true); // retained
 Console.WriteLine("msgId " + msgId);
 client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;

 void client_MqttMsgPublished(object sender, MqttMsgPublishedEventArgs e)
 {
   Debug.WriteLine("MessageId = " + e.MessageId + " Published = " + e.IsPublished);
   Console.WriteLine("MessageId = " + e.MessageId + " Published = " + e.IsPublished);
 }

 void client_MqttMsgSubscribed(object sender, MqttMsgSubscribedEventArgs e)
 {
   Debug.WriteLine("Subscribed for id = " + e.MessageId);
   Console.WriteLine("Subscribed for id = " + e.MessageId);
 }

 void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
 {
   Debug.WriteLine("Received = " + Encoding.UTF8.GetString(e.Message) + " on topic " + e.Topic);
   Console.WriteLine("Received = " + Encoding.UTF8.GetString(e.Message) + " on topic " + e.Topic);
 }

}

订阅者代码:

mosquitto_sub -h broker.hivemq.com -t mytopic(terminal)

当我运行此应用程序时,该消息会发送给订阅者但是当我尝试从终端发布消息时,我的应用程序没有收到任何消息

在终端发布的代码

mosquitto_pub -h broker.hivemq.com -t mytopic -m "Hai this is sample"

那么如何从终端接收已发布的消息?

我使用mqtt客户端作为MqttClient client = new MqttClient("broker.hivemq.com");

当我尝试更改我的IP地址时,它没有像

那样出现错误
 Unhandled Exception: System.AggregateException: One or more errors occurred. (No such host is known) ---> System.Net.Sockets.SocketException: No such host is known

1 个答案:

答案 0 :(得分:1)

使用以下代码正常工作

string[] topic = { "mytopic"};
byte[] qosLevels = { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE };
client.Subscribe(topic, qosLevels);

我的代码中缺少上面的代码。终端到c#console和c#console到终端。