前言
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.");
}
}
}