mqttnet 2.8.5 客户端代码实现

第一步:

nuget软件包中搜索安装mqttnet 2.8.5

第二步:编写测试代码

using MQTTnet;
using MQTTnet.Client;

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace mqtt工具
{
    public partial class Form1 : Form
    {

        MqttFactory factory;
        IMqttClient mqttClient;
        MqttClientConnectResult ret;
        IMqttClientOptions options;
        async void myinit()
        {
             factory= new MqttFactory();
             mqttClient= factory.CreateMqttClient();
            options = new MqttClientOptionsBuilder()
            .WithClientId("Client1")//id
            .WithTcpServer("test.com")//服务器地址
            .WithCredentials("admin", "123456")//用户名密码
            .WithKeepAlivePeriod(new System.TimeSpan(1000000))
            .WithCleanSession()
            .Build();
           
            
            
            mqttClient.ApplicationMessageReceived += (s, e) =>
            {
                Console.WriteLine("### RECEIVED APPLICATION MESSAGE ###");
                Console.WriteLine($"+ Topic = {e.ApplicationMessage.Topic}");
                Console.WriteLine($"+ Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
                Console.WriteLine($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}");
                Console.WriteLine($"+ Retain = {e.ApplicationMessage.Retain}");
                Console.WriteLine();
            };

            mqttClient.Connected += async (s, e) =>
            {
                Console.WriteLine("### CONNECTED WITH SERVER ###");

                // Subscribe to a topic
                await mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic("device/msg").Build());

                Console.WriteLine("### SUBSCRIBED ###");
            };
            mqttClient.Disconnected += MqttClient_Disconnected;
            ret=await mqttClient.ConnectAsync(options);
        }

        private void MqttClient_Disconnected(object sender, MqttClientDisconnectedEventArgs e)
        {
            //throw new NotImplementedException();
            Console.WriteLine("disconnect!!!");
        }

        public Form1()
        {
            InitializeComponent();
            myinit();
        }

        private void button1_发送_Click(object sender, EventArgs e)
        {
            mqttClient.PublishAsync("device","sdfdsafsa");
        }
    }
}

 

你可能感兴趣的:(物联网)