上一篇写服务端的文章已经是去年年底,现在MQTTnet的版本是4.2.1.781,总的来说改动不大。下面以新版为例实现一个客户端。

var mqttClientOptions = new MqttClientOptionsBuilder()
            .WithTcpServer("地址", 端口)
            .WithClientId("我是客户端名称")//连接id
            .WithCredentials("demo","123456")//如果有用户名密码
            .WithTls()//如果启用了ssl/tls
            .WithProtocolVersion(MqttProtocolVersion.V500)//如果用mqtt5
            .Build();//配置
        IMqttClient client = new MqttFactory().CreateMqttClient();//创建连接
        client.ApplicationMessageReceivedAsync += MqttClient_ApplicationMessageReceivedAsync;//收到消息的方法
        client.ConnectedAsync += Client_ConnectedAsync;//连接成功的方法
        client.ConnectingAsync += Client_ConnectingAsync;//连接中的方法

配置里面一个大坑害我调了一个小时,如果mqtt服务端需要用户名和密码,那么使用.WithCredentials()来填写。我一直以为是.WithUserProperty(),极有迷惑性。

连接并订阅主题

// User proper cancellation and no while(true).
                while (true)
                {
                    try
                    {
                        // This code will also do the very first connect! So no call to _ConnectAsync_ is required in the first place.
                        if (!await client.TryPingAsync())
                        {
                            var response= await client.ConnectAsync(mqttClientOptions, CancellationToken.None);
                            DelegateSetRtbText(response.ReasonString);
                            // Subscribe to topics when session is clean etc.
                            var mqttSubscribeOptions = new MqttFactory().CreateSubscribeOptionsBuilder()
                            .WithTopicFilter(
                                f =>
                                {
                                    f.WithTopic("shi");//订阅主题
                                })
                            .Build();
                            await client.SubscribeAsync(mqttSubscribeOptions);
                        }
                    }
                    catch
                    {
                        // Handle the exception properly (logging etc.).
                    }
                    finally
                    {
                        // Check the connection state every 5 seconds and perform a reconnect if required.
                        await Task.Delay(TimeSpan.FromSeconds(5));
                    }
                }

好了,就这么简单

最后修改:2023 年 08 月 18 日
如果觉得我的文章对你有用,请随意赞赏