最近学习需要在Unity中用到MQTT通信,CSDN下载了一些资料都有报错(主要是也不太看得懂代码不会改),跟B站up复现了一个简单的demo算是加深了一些学习,有需要的初学者可以自取。
demo实现步骤大致如下
1.HslCommunication组件添加
要先下载个HslCommunication,选中文件夹里这俩个文件直接拖到unity里就行
2.Unity创建脚本文件,编译后直接扔摄像头上就完事儿了,上代码,Topic根据需求进行更改
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using HslCommunication.MQTT;
using System.Text;
using System.Diagnostics;
using System;
public class mqtt_test : MonoBehaviour
{
private MqttClient mqttClient;
// Start is called before the first frame update
void Start()
{
mqttClient = new MqttClient(new MqttConnectionOptions()
{
ClientId = "ABC", // 客户端的唯一的ID信息
IpAddress = "127.0.0.1", // 服务器的地址
});
// 连接服务器
HslCommunication.OperateResult connect = mqttClient.ConnectServer();
if (connect.IsSuccess)
{
// 连接成功
UnityEngine.Debug.Log("连接成功");
}
else
{
// 连接失败,过会就需要重新连接了
UnityEngine.Debug.Log("连接失败");
}
// 然后添加订阅
HslCommunication.OperateResult sub = mqttClient.SubscribeMessage("test");
if (sub.IsSuccess)
{
// 订阅成功
UnityEngine.Debug.Log("订阅成功");
}
else
{
// 订阅失败
UnityEngine.Debug.Log("订阅失败");
}
// 订阅示例
mqttClient.OnMqttMessageReceived += (MqttClient client, string topic, byte[] payload) =>
{
//Console.WriteLine("Time:" + DateTime.Now.ToString());
//Console.WriteLine("Topic:" + topic);
//Console.WriteLine("Payload:" + Encoding.UTF8.GetString(payload));
UnityEngine.Debug.Log("Time:" + DateTime.Now.ToString());
UnityEngine.Debug.Log("Topic:" + topic);
UnityEngine.Debug.Log("Payload:" + Encoding.UTF8.GetString(payload));
};
}
// Update is called once per frame
void Update()
{
if(Input.GetKey(KeyCode.Space))
{
HslCommunication.OperateResult connect = mqttClient.PublishMessage(new MqttApplicationMessage()
{
Topic = "/AAA", //主题
QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce, //如果是实时数据,适合用这个
Payload = Encoding.UTF8.GetBytes("Test data")
});
if(connect.IsSuccess)
{
//发布成功
UnityEngine.Debug.Log("发布成功");
}
else
{
UnityEngine.Debug.Log("发布失败");
}
}
}
}
3.(1)在Unity里运行场景
(2)与MQTTX进行联调(MQTTfx也行),地址一致,主题对应就行
订阅MQTTX的主题
按空格发布消息“Test data”,MQTTX订阅Unity端的主题,接收发布的消息成功