首页 > 其他分享 >MqttNet version 4.1.3.563 Basic example

MqttNet version 4.1.3.563 Basic example

时间:2023-07-11 19:13:10浏览次数:43  
标签:mqttClient 3.563 share MqttNet version sheet new data se

@@mqttnet 4.1.4 The formal environment cannot receive messages

 

 

1

Following this example I have now therefore been required to update the MQTT.NET from version 3 (that works thanks the provided help) to version 4.

A very basic set of capabilities would be enough:

  1. Connect to an adress with a timeout
  2. Check if the connection has gone well
  3. Receive messages
  4. check disconnection

that was extremely easy in version 3

MqttClientOptionsBuilder builder = new MqttClientOptionsBuilder()
                                .WithClientId("IoApp" + HelperN.MQTT.GetClientID(true))
                                .WithTcpServer("localhost", 1883);

ManagedMqttClientOptions options = new ManagedMqttClientOptionsBuilder()
                                .WithAutoReconnectDelay(TimeSpan.FromSeconds(60))
                                .WithClientOptions(builder.Build())
                                .Build();

mqttClient = new MqttFactory().CreateManagedMqttClient();

mqttClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(OnConnected);
mqttClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(OnDisconnected);
mqttClient.ConnectingFailedHandler = new ConnectingFailedHandlerDelegate(OnConnectingFailed);

mqttClient.SubscribeAsync(...);
mqttClient.SubscribeAsync(...);
mqttClient.StartAsync(options).GetAwaiter().GetResult();

mqttClient.UseApplicationMessageReceivedHandler(args => { OnMessageReceived(args); });

but when it comes to version 4 if I have to relay on those examples I have problems. Let's start from the connection

public static async Task Connect_Client_Timeout()
{
    /*
     * This sample creates a simple MQTT client and connects to an invalid broker using a timeout.
     * 
     * This is a modified version of the sample _Connect_Client_! See other sample for more details.
     */

    var mqttFactory = new MqttFactory();
    strError = String.Empty;

    using (var mqttClient = mqttFactory.CreateMqttClient())
    {
        var mqttClientOptions = new MqttClientOptionsBuilder().WithTcpServer("aaaa127.0.0.1",1883).Build();

        try
        {
                
            using (var timeoutToken = new CancellationTokenSource(TimeSpan.FromSeconds(5)))
            {
                await mqttClient.ConnectAsync(mqttClientOptions, timeoutToken.Token);
            }
        }
        catch (OperationCanceledException exc)
        {
            strError = "Connect_Client_Timeout exc:" + exc.Message;
        }
    }
}

And I call this task from the main awaiting the result.

var connectTask  = Connect_Client_Timeout();
connectTask.Wait();<-----never ends

Since I put a wrong address "aaaa127.0.0.1" I expect a failure after 5 seconds. But the connectTask.Wait never end. But even if I put the right address "127.0.0.1" it never exits. So perhaps the error stands in the connectTask.Wait();.

Thanks

Share Improve this question   edited Dec 21, 2022 at 11:03     asked Dec 21, 2022 at 10:37 Luca's user avatar Luca 89811 gold badge1313 silver badges3030 bronze badges Add a comment

1 Answer

2  

The solution is here In short you have to do this:

static async Task  Connect()
{
    IManagedMqttClient _mqttClient = new MqttFactory().CreateManagedMqttClient();

    // Create client options object
    MqttClientOptionsBuilder builder = new MqttClientOptionsBuilder()
                                        .WithClientId("behroozbc")
                                        .WithTcpServer("localhost");
    ManagedMqttClientOptions options = new ManagedMqttClientOptionsBuilder()
                                .WithAutoReconnectDelay(TimeSpan.FromSeconds(60))
                                .WithClientOptions(builder.Build())
                                .Build();



    // Set up handlers
    _mqttClient.ConnectedAsync += _mqttClient_ConnectedAsync;


    _mqttClient.DisconnectedAsync += _mqttClient_DisconnectedAsync;


    _mqttClient.ConnectingFailedAsync += _mqttClient_ConnectingFailedAsync;


    // Connect to the broker
    await _mqttClient.StartAsync(options);

    // Send a new message to the broker every second
    while (true)
    {
        string json = JsonSerializer.Serialize(new { message = "Hi Mqtt", sent = DateTime.UtcNow });
        await _mqttClient.EnqueueAsync("behroozbc.ir/topic/json", json);

        await Task.Delay(TimeSpan.FromSeconds(1));
    }
    Task _mqttClient_ConnectedAsync(MqttClientConnectedEventArgs arg)
    {
        Console.WriteLine("Connected");
        return Task.CompletedTask;
    };
    Task _mqttClient_DisconnectedAsync(MqttClientDisconnectedEventArgs arg)
    {
        Console.WriteLine("Disconnected");
        return Task.CompletedTask;
    };
    Task _mqttClient_ConnectingFailedAsync(ConnectingFailedEventArgs arg)
    {
        Console.WriteLine("Connection failed check network or broker!");
        return Task.CompletedTask;
    }
}

and then just call Connect() and rely on the subscribed examples

Share Improve this answer   answered Dec 21, 2022 at 12:56    

MQTT Client with MQTTnet 4 and C#

TABLE OF CONTENTS

In the previous post, we worked with MQTTnet version 3, although version 4 of MQTTnet came in Jun 2022. As MQTTnet version 4 has a lot of changes, I thought it would be helpful to write a new article about developing a simple MQTT client using this version. To find more information on MQTT and what is MQTT client and broker please check this post.

We need to create a console project. I use dotnet CLI to create a new project.

dotnet new console --name SimpleMQTTClient4

Now We have a new empty project to code an MQTT client.

To work in dotnet with MQTT Client, we need to install the MQTTnet.Extensions.ManagedClient package from NuGet. This article uses version 4.

dotnet add package MQTTnet.Extensions.ManagedClient --version 4.0.2.221

Open Program.cs.Add the below code.

using MQTTnet.Client;
using MQTTnet.Extensions.ManagedClient;
using MQTTnet;
using System.Text.Json;

IManagedMqttClient _mqttClient = new MqttFactory().CreateManagedMqttClient();

// Create client options object
MqttClientOptionsBuilder builder = new MqttClientOptionsBuilder()
                                        .WithClientId("behroozbc")
                                        .WithTcpServer("localhost");
ManagedMqttClientOptions options = new ManagedMqttClientOptionsBuilder()
                        .WithAutoReconnectDelay(TimeSpan.FromSeconds(60))
                        .WithClientOptions(builder.Build())
                        .Build();



// Set up handlers
_mqttClient.ConnectedAsync += _mqttClient_ConnectedAsync;


_mqttClient.DisconnectedAsync += _mqttClient_DisconnectedAsync;


_mqttClient.ConnectingFailedAsync += _mqttClient_ConnectingFailedAsync;


// Connect to the broker
await _mqttClient.StartAsync(options);

// Send a new message to the broker every second
while (true)
{
    string json = JsonSerializer.Serialize(new { message = "Hi Mqtt", sent = DateTime.UtcNow });
    await _mqttClient.EnqueueAsync("behroozbc.ir/topic/json", json);

    await Task.Delay(TimeSpan.FromSeconds(1));
}
Task _mqttClient_ConnectedAsync(MqttClientConnectedEventArgs arg)
{
    Console.WriteLine("Connected");
    return Task.CompletedTask;
};
Task _mqttClient_DisconnectedAsync(MqttClientDisconnectedEventArgs arg)
{
    Console.WriteLine("Disconnected");
    return Task.CompletedTask;
};
Task _mqttClient_ConnectingFailedAsync(ConnectingFailedEventArgs arg)
{
    Console.WriteLine("Connection failed check network or broker!");
    return Task.CompletedTask;
}

By default MQTT without encryption port is 1883. If you want to change it, add a parameter port number to WithTcpServer.

// Create the options for MQTT Broker
var options = new MqttServerOptionsBuilder()
    //Set endpoint to localhost
    .WithDefaultEndpoint()
    // Port is going to use 5004
    .WithDefaultEndpointPort(5004);

You have an MQTT client. I hope it was helpful. In this post, I will show you how to create a broker to test it.

You find this project on Github.

If you are still unsure of what to do or if you got any errors, I suggest you use the comment section below and let me know! I’m here to help.

     

标签:mqttClient,3.563,share,MqttNet,version,sheet,new,data,se
From: https://www.cnblogs.com/wl-blog/p/17545698.html

相关文章

  • CF1702G2 Passable Paths (hard version)
    PassablePaths(hardversion)思路题意:判断是否存在一条链包含树上给定点集。考虑把\(1\)当做树的根,将无根树转化为有根树。考虑这样一个性质:若存在满足条件的最短链,则点集中深度最深的点\(u\)是该链的一个端点,点集中距离\(u\)最远的点\(v\)是该链的另一端点。证明......
  • 牛客练习赛113 D 小红的数组操作(hard version)
    题目要求求出最小的总代价使得平均数为整数,转换式子可得实际就是求出a,b使得(a*x-b*y+sum)%n==0且a*p+b*q要最小,平均值的为sum/n,因此对sum进行操作使其成为n的倍数即可(a*x-b*y+sum)%n==0=>((a*x+sum)%n-b*y%n)%n==0因为(a*x+sum)%n<n,b*y%n<n,因此要想二者差求余数为0一定为(......
  • 华为超算平台git、cmake、wget、curl报错:SSLv3_client_method version OPENSSL_1_1_0
    最近在使用超算平台时报错,不管是git、cmake、wget、curl中的哪个都报错,大致错误: /usr/bin/cmake3:relocationerror:/usr/lib64/libcurl.so.4:symbolSSLv3_client_methodversionOPENSSL_1_1_0notdefinedinfilelibssl.so.1.1withlinktimereference  参考网......
  • this version of the Java Runtime only recognizes class file versions up to 55.0
    问题:  运行SpringBootdemo时报错: thisversionoftheJavaRuntimeonlyrecognizesclassfileversionsupto55.0at原因:   编译版本和运行版本不一致,具体原因是编译版本高于运行版本,SpringBootdemo中使用的是jdk17,我本地的jdk是11 解决:  调整idea中的jd......
  • 2023-05-02-Unit-Root-Inversion
    Andtryingtofigureoutwhatit'slikemovingon.Summary\[[n\midk]=\frac{1}{n}\sum_{i=0}^{n-1}\omega^{ik}_{n}\]九个太阳\[\begin{aligned}&\sum_{i=0}^{n}\binom{n}{i}\frac{1}{k}\sum_{j=0}^{k-1}\omega_{k}^{ij}\......
  • javax.net.ssl.SSLHandshakeException: The server selected protocol version TLS10
    问题:报错:javax.net.ssl.SSLHandshakeException:TheserverselectedprotocolversionTLS10isnotacceptedbyclientpreferences[TLS12]解决方式:1、修改%JAVA_HOME%/jre/lib/security/java.security2、修改内容:jdk.tls.disabledAlgorithms删除TLSv13、删除前: https:......
  • MQTTnet 创建基于 WebSocket 的 Mqtt 服务器
    MQTTnet.Exceptions.MqttProtocolViolationException:Expectedatleast21540bytesbutthereareonly71bytes使用了错误的协议,mqtt有tcp和ws两种连接协议ws://使用1883端口就能正常连接 ......
  • spring报错-Caused by: java.lang.IllegalArgumentException: Unsupported class file
    这个错误原因是因为JDK版本过高,改一下版本就行了把里面的19改成8这样就行了......
  • 什么是 ABAP Domain 的 Conversion Routine
    ABAP(AdvancedBusinessApplicationProgramming)是一种高级业务应用编程语言,由德国软件公司SAPSE开发。ABAP用于开发和定制SAPERP系统。在SAPERP系统中,数据的组织和存储通过数据字典(DataDictionary)进行管理。数据字典中的一个重要组成部分是Domain。Domain是一个抽象层,用于定......
  • CF1637H Minimize Inversions Number
    我直接??????????????????考虑一个数怎么做,就是逆序对减去一个\(i\)前面的逆序对再加上顺序对。考虑很多数怎么做,就是这个玩意的和再加上子序列种的顺序对减去逆序对,顺序对可以用逆序对表示,现在只考虑顺序对。注意到,如果\(i<j,p_i>p_j\)且\(i\)在子序列中\(j\)不在子序列中,那么把\(j\)弄......