简体   繁体   English

使用C#实现MQTT客户端以连接外部MQTT代理

[英]Implement MQTT client using C# to connect external MQTT broker

I'm really new to MQTT protocol and do some tests in ubuntu and openwrt platforms using terminal commands. 我是MQTT协议的新手,并使用终端命令在ubuntu和openwrt平台上进行一些测试。 I have successfully install opensource MQTT broker Mosquitto on openwrt chaos calmer and I now able to publish/subscribe topic using two different terminal windows. 我已经在openwrt chaos calmer上成功安装了开源MQTT代理Mosquitto,现在我可以使用两个不同的终端窗口发布/订阅主题。 Im planning to build a simple GUI application with minimal user interface to publish the MQTT message. 我打算用最少的用户界面构建一个简单的GUI应用程序来发布MQTT消息。 I saw that M2Mqtt library for support. 我看到了M2Mqtt库的支持。 But when it comes to the documentation there is no proper guidance for how to connect external MQTT broker. 但是,当涉及到文档时,没有关于如何连接外部MQTT代理的正确指导。

I followed this document http://www.hivemq.com/blog/mqtt-client-library-encyclopedia-m2mqtt 我按照这个文件http://www.hivemq.com/blog/mqtt-client-library-encyclopedia-m2mqtt

How can I publish message to MQTT broker hosted externally (in my case virtualbox - on top of openwrt ) with C# ? 如何使用C#将消息发布到外部托管的MQTT代理(在我的案例中,虚拟框 - 在openwrt之上)?

The Link you mentioned already contains your answer. 您提到的链接已包含您的答案。

To connect to the MQTT broker: 要连接到MQTT代理:

MqttClient client = new MqttClient("broker.hivemq.com");
byte code = client.Connect(Guid.NewGuid().ToString());

To publish a message, do the following: 要发布消息,请执行以下操作:

ushort msgId = client.Publish("/my_topic", // topic
                              Encoding.UTF8.GetBytes("MyMessageBody"), // message body
                              MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, // QoS level
                              false); // retained

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM