61 lines
1.7 KiB
C#
61 lines
1.7 KiB
C#
using UnityEngine;
|
|
using System;
|
|
using uPLibrary.Networking.M2Mqtt;
|
|
using uPLibrary.Networking.M2Mqtt.Messages;
|
|
using System.Threading.Tasks;
|
|
|
|
public class MqttHslClient : MonoBehaviour
|
|
{
|
|
private MqttClient mqttClient;
|
|
public string brokerAddress = "172.16.1.104";//代理的地址
|
|
public int brokerPort = 8083;//代理端口
|
|
private string[] topic = { "car1", "car2", "car3", "car4", "car5" }; // 订阅的多个主题
|
|
|
|
async void Start()
|
|
{
|
|
await Task.Run(() =>
|
|
{
|
|
ConnectToMqttServer();
|
|
});
|
|
|
|
}
|
|
public void ConnectToMqttServer()
|
|
{
|
|
for (int i = 0; i < topic.Length; i++)
|
|
{
|
|
Debug.Log(topic[i]);
|
|
}
|
|
// 创建 MQTT 客户端实例
|
|
mqttClient = new MqttClient(brokerAddress, brokerPort, false, null, null, MqttSslProtocols.None);
|
|
|
|
// 注册消息处理函数
|
|
mqttClient.MqttMsgPublishReceived += OnMqttMsgPublishReceived;
|
|
|
|
// 连接到 MQTT 代理
|
|
mqttClient.Connect(Guid.NewGuid().ToString());
|
|
|
|
// 订阅多个主题
|
|
|
|
byte[] qosLevels = { MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE, MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE, MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE, MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE, MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE };
|
|
mqttClient.Subscribe(topic, qosLevels);
|
|
}
|
|
private void OnMqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
|
|
{
|
|
string message = System.Text.Encoding.UTF8.GetString(e.Message);
|
|
Debug.Log($"Received message from topic {e.Topic}: {message}");
|
|
// 处理接收到的消息
|
|
}
|
|
/// <summary>
|
|
/// 结束时释放内存
|
|
/// </summary>
|
|
void OnDestroy()
|
|
{
|
|
if (mqttClient != null && mqttClient.IsConnected)
|
|
{
|
|
mqttClient.Disconnect();
|
|
}
|
|
}
|
|
}
|
|
|
|
|