using UnityEngine; using System; using System.Threading; using System.Threading.Tasks; using MQTTnet; using MQTTnet.Client; using MQTTnet.Protocol; public class MqttHslClient : MonoBehaviour { private MqttFactory mqttFactory = new MqttFactory(); private IMqttClient mqttClient; void Start() { mqttClient = mqttFactory.CreateMqttClient(); Task.Run(async () => await ConnectToMqttBrokerAsync()); } private async Task ConnectToMqttBrokerAsync() { try { var options = new MqttClientOptionsBuilder() .WithTcpServer("172.16.1.104", 8083) // 使用 HiveMQ 公共代理 .WithClientId(Guid.NewGuid().ToString()) .WithCleanSession() .Build(); //连接 var response = await mqttClient.ConnectAsync(options, CancellationToken.None); Debug.Log(("The MQTT client is connected.") + mqttClient.IsConnected); //生成订阅 var topicFilter = new MqttTopicFilterBuilder() .WithTopic("car8") .WithQualityOfServiceLevel(MqttQualityOfServiceLevel.ExactlyOnce) .Build(); await mqttClient.SubscribeAsync(topicFilter); mqttClient.ApplicationMessageReceivedAsync += (e => { var topic = e.ApplicationMessage.Topic; var payload = System.Text.Encoding.UTF8.GetString(e.ApplicationMessage.PayloadSegment.Array); Debug.Log($"Topic is {topic}, Payload is {payload}"); return Task.CompletedTask; }); } catch (Exception e) { Debug.Log(e.Message); } } private void HandleReceivedMessage(MqttApplicationMessageReceivedEventArgs e) { // 接收到 MQTT 消息时的处理逻辑 string topic = e.ApplicationMessage.Topic; string payload = System.Text.Encoding.UTF8.GetString(e.ApplicationMessage.Payload); Debug.Log($"Received message from topic '{topic}': {payload}"); // 如果消息是 JSON 格式,可以进行 JSON 解析 try { //MyDataObject data = JsonUtility.FromJson(payload); // 现在您可以使用 data 对象中的数据 //Debug.Log($"Parsed JSON: {data}"); } catch (Exception ex) { Debug.LogError($"Failed to parse JSON: {ex.Message}"); } } void Update() { } private void OnDestroy() { } }