Unity MQTT客户端连接方式

MQTTnet.Extensions.ManagedClient

一、MQTT客户端简单暴力版

可将以下代码直接挂在物体上使用

using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Extensions.ManagedClient;
using MQTTnet.Protocol;
using QFramework;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using UnityEngine;

public class UDPDataMqtt : MonoBehaviour
{
   
    string[] topicArray;

    //private IMqttClient m_mqttClient = null;

    private IManagedMqttClient m_managedmqttClient;
    private MqttFactory Factory = new MqttFactory();
    /// <summary>
    /// 操作参数
    /// </summary>
    private MqttClientOptions Options;

    /// <summary>
    /// 消息参数
    /// </summary>
    private ManagedMqttClientOptions ManagedOptions;

    // Start is called before the first frame update
    async void Start()
    {
     //将XML文件加载进来
        XDocument document = XDocument.Load(CommonInfo.NetWorkSettingPath + "/MqttSConfig.xml");
        //获取到XML的根元素进行操作
        XElement root = document.Root;
        XElement ele = root.Element("MqttConfig");


        //获取心跳包时间间隔
        XAttribute Topic = ele.Attribute("MQTTDataTopics");

        if (!string.IsNullOrEmpty(Topic.Value))
        {
   
            topicArray = Topic.Value.Split(new char[] {
    ';' }, StringSplitOptions.RemoveEmptyEntries);
        }


        await ConnectMqttServerAsync();
    }


    /// <summary>
    /// 客户端初始化
    /// </summary>
    public void Client_Init()
    {
   
        
        //配置初始化
        //配置连接参数
        Options = new MqttClientOptionsBuilder()
              .WithTcpServer("127.0.0.1", 1883) //服务器地址端口号
            .WithClientId("JiJuReceiveData")  //连接客户端id
            .WithCredentials("", "")    //用户名账号密码  没有可不填
            .WithWillQualityOfServiceLevel(MqttQualityOfServiceLevel.AtMostOnce)
            // .WithCleanSession()
            .WithKeepAlivePeriod(TimeSpan.FromSeconds(5))
            .Build();

        //配置重连机制
        ManagedOptions = new ManagedMqttClientOptionsBuilder()
            .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
            .WithClientOptions(Options)
            .Build();

        //创建客户端
        m_managedmqttClient = Factory.CreateManagedMqttClient();
        //配置数据接收事件
        m_managedmqttClient.ApplicationMessageReceivedAsync += Receive_Event;
        m_managedmqttClient.ConnectedAsync += Connected_Event;
        m_managedmqttClient.DisconnectedAsync += Disconnected_Event;

    }

    public async Task ConnectMqttServerAsync()
    {
   

        Client_Init();

        try
        {
   
            //订阅主题
          
            if (topicArray.Length > 0)
            {
   
                await m_managedmqttClient.SubscribeAsync(
                    topicArray.Select(t => new MqttTopicFilterBuilder().WithTopic(t).WithAtLeastOnceQoS().Build()).ToArray()
                    );
            }
            //连接服务器
            await m_managedmqttClient.StartAsync(ManagedOptions);

        }
        catch (Exception e)
        {
   
            Console.WriteLine(e);
        }

        #region m_mqttClient

        //配置连接参数
        //var options = new MqttClientOptionsBuilder()
        //    .WithTcpServer("127.0.0.1", 1883)
        //    .WithClientId(Guid.NewGuid().ToString())
        //     .WithCleanSession()
        //     .WithKeepAlivePeriod(TimeSpan.FromSeconds(5))
        //    .Build();
        //if (m_mqttClient == null)
        //{
   
        //    m_mqttClient = new MqttFactory().CreateMqttClient();


        //    //  MqttServerOptions mqttServerOptions = new MqttServerOptions();
        //    //   mqttServer = new MqttFactory().CreateMqttServer(mqttServerOptions);
        //}

        // await m_mqttClient.ConnectAsync(options);
        
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

杰尼杰尼丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值