在 Unity 中使用 MQTTnet


前言

2025年3月24日

Unity 2022.3.54f1


MQTT X

桌面客户端,用于查看和测试 MQTT
官网地址:https://mqttx.app/


免费的公共 MQTT 服务器

官网地址:https://www.emqx.com/zh/mqtt/public-mqtt5-broker

Broker:broker.emqx.io
TCP 端口:1883
主题:testtopic/#(注意默认禁止了 $SYS 主题和 # 主题,此处可换为其他的,还挺多的 test 之类的)
MQTT版本:5.0


MQTTnet.dll

两种方式导入 MQTTnet ,
1、从 nuget.org 把包下载下来,解压后将对应平台的 dll 从 lib 文件夹中取出来,放到 Plugins 文件夹。
2、为 Unity 安装 NuGetForUnity 包管理器,通过它搜索 MQTTnet 安装。

注意 dll 的版本的依赖,是否为 Unity 所支持

Unity3D 入门:为 Unity 的 C# 项目添加 dll 引用或安装 NuGet 包
Unity3D 入门:如何管理 Unity 项目中的 NuGet 包?使用第三方 NuGet 包管理器——NuGetForUnity


一、自行下载、解压、导入

下载依赖包含 .NETStandard 2.1 的 mqttnet.4.3.7.1207.nupkg

最新的 5.0 只依赖 .net8.0 , Unity 里面用不了

将下载好的文件后缀改为 zip ,并解压。

根据 Unity 中设置的 API 兼容性级别 ,找到对应的 lib 文件夹下的 dll 放到 Plugins 文件夹中。

F:\mqttnet.4.3.7.1207\lib\netstandard2.1\MQTTnet.dll


二、安装 NuGetForUnity ,导入

去这里下载最新的Release
https://github.com/GlitchEnzo/NuGetForUnity

导入后,Unity 上方工具栏点击 NuGet / Manage NuGet Packages,找到对应版本的 MQTTnet ,Install


三、代码示例

using System;
using System.Threading.Tasks;
using UnityEngine;
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Exceptions;

public class MQTTManager : MonoBehaviour
{
    private IMqttClient mqttClient;
    public string brokerAddress = "broker.emqx.io"; // Change to your broker address
    public int brokerPort = 1883; // Default MQTT port
    public string topic = "testtopic/#";

    public MQTTnet.Formatter.MqttProtocolVersion mqttProtocolVersion = MQTTnet.Formatter.MqttProtocolVersion.V500;

    private void Start()
    {
        InitializeMQTTClient();
    }

    private async void InitializeMQTTClient()
    {
        mqttClient = new MqttFactory().CreateMqttClient();

        var options = new MqttClientOptionsBuilder()
            .WithClientId("UnityClient_" + Guid.NewGuid())
            .WithTcpServer(brokerAddress, brokerPort)
            .WithProtocolVersion(mqttProtocolVersion)
            .Build();


        mqttClient.ApplicationMessageReceivedAsync += MqttClient_ApplicationMessageReceivedAsync;
        mqttClient.ConnectedAsync += MqttClient_ConnectedAsync;
        mqttClient.DisconnectedAsync += MqttClient_DisconnectedAsync;

        try
        {
            await mqttClient.ConnectAsync(options);
            Debug.Log("Connected to MQTT broker.");
            SubscribeToTopic(topic); // Change to your topic
        }
        catch (MqttProtocolViolationException ex)
        {
            Debug.LogError($"Protocol error: {ex.Message}");
        }
        catch (Exception ex)
        {
            Debug.LogError($"Could not connect to MQTT broker: {ex.Message}");
        }
    }

    private Task MqttClient_DisconnectedAsync(MqttClientDisconnectedEventArgs arg)
    {
        return Task.CompletedTask;
    }

    private Task MqttClient_ConnectedAsync(MqttClientConnectedEventArgs arg)
    {
        return Task.CompletedTask;
    }

    private Task MqttClient_ApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs arg)
    {
        Debug.Log(arg.ApplicationMessage.Topic);
        Debug.Log(arg.ApplicationMessage.ConvertPayloadToString());

        return Task.CompletedTask;
    }

    public async void PublishMessage(string topic, string message)
    {
        if (mqttClient.IsConnected)
        {
            var mqttMessage = new MqttApplicationMessageBuilder()
                .WithTopic(topic)
                .WithPayload(message)
                .WithQualityOfServiceLevel(MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce)
                .WithRetainFlag()
                .Build();

            await mqttClient.PublishAsync(mqttMessage);
            Debug.Log($"Published message: {message} to topic: {topic}");
        }
        else
        {
            Debug.LogWarning("MQTT client is not connected.");
        }
    }

    public async void SubscribeToTopic(string topic)
    {
        if (mqttClient.IsConnected)
        {
            var topicFilter = new MqttTopicFilterBuilder()
                .WithTopic(topic)
                .Build();

            await mqttClient.SubscribeAsync(topicFilter);
            Debug.Log($"Subscribed to topic: {topic}");
        }
        else
        {
            Debug.LogWarning("MQTT client is not connected.");
        }
    }

    private async void OnApplicationQuit()
    {
        if (mqttClient != null)
        {
            await mqttClient.DisconnectAsync();
            Debug.Log("Disconnected from MQTT broker.");
        }
    }
}
### 如何在 Unity使用 MQTTnet 库进行消息通信 #### 创建项目并导入库文件 要在Unity中利用MQTTnet库创建一个MQTT客户端,首先需要确保已安装最新版的Unity编辑器。接着,在项目的`Assets/Plugins`目录下引入适用于.NET Standard 2.0或更高版本的MQTTnet NuGet包[^1]。 #### 初始化 MQTT 客户端实例 通过C#脚本初始化一个新的MQTT客户端对象,并配置连接参数: ```csharp using MqttClient = MQTTnet.Client.MqttFactory; // ... private IMqttClient _mqttClient; void Start() { var factory = new MqttClient(); _mqttClient = factory.CreateMqttClient(); // 设置连接选项 var options = new MqttClientOptionsBuilder() .WithTcpServer("broker.hivemq.com") // 替换成实际Broker地址 .WithClientId(Guid.NewGuid().ToString()) .Build(); } ``` #### 建立与 Broker 的连接 调用ConnectAsync方法来建立到指定代理服务器(Broker)的链接: ```csharp async void ConnectToBroker(){ try{ await _mqttClient.ConnectAsync(options); Debug.Log("Connected to broker."); } catch(Exception ex){ Debug.LogError($"Failed to connect: {ex.Message}"); } } ``` #### 订阅主题并处理接收到的消息 定义回调函数以响应来自特定主题的新数据;订阅感兴趣的主题以便接收更新: ```csharp _mqttClient.UseApplicationMessageReceivedHandler(e => { string payload = Encoding.UTF8.GetString(e.ApplicationMessage.Payload); Debug.Log($"Received message on topic '{e.ApplicationMessage.Topic}': {payload}"); }); var subscribeOpts = new TopicFilterBuilder().WithTopic("#").ExactlyOnce().Build(); await _mqttClient.SubscribeAsync(subscribeOpts); Debug.Log("Subscribed successfully"); ``` #### 发布消息至目标主题 当应用程序中有新事件发生时,可以向其他设备广播通知或其他形式的信息: ```csharp public async Task PublishMessage(string topic, string content){ var msg = new MqttApplicationMessageBuilder() .WithTopic(topic) .WithPayload(content) .AtLeastOnce() .Build(); await _mqttClient.PublishAsync(msg); Debug.Log($"Published [{content}] under topic [{topic}]"); } ``` 以上就是在Unity环境下基于MQTTnet库构建基本消息传递系统的指南。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值