using MQTTnet.Client; using MQTTnet; using System.Text; using System.Threading; using System.Threading.Tasks; using UnityEngine; using System; public class Mqtttest : MonoBehaviour { private IMqttClient mqttClient; private async void Start() { // MQTT 服务器地址和端口 string brokerAddress = "tcp://mqtt.server.com:1883"; string clientId = Guid.NewGuid().ToString(); // MQTT 连接选项 var options = new MqttClientOptionsBuilder() .WithTcpServer(brokerAddress) .WithClientId(clientId) .Build(); mqttClient = new MqttFactory().CreateMqttClient(); } // 事件处理程序:连接成功时 // mqttClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(async e => // { // Debug.Log("Connected to MQTT broker."); // await mqttClient.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic("your/topic").Build()); // Debug.Log("Subscribed to topic 'your/topic'."); // }); // // 事件处理程序:接收到消息时 // mqttClient.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(e => // { // string topic = e.ApplicationMessage.Topic; // string payload = Encoding.UTF8.GetString(e.ApplicationMessage.Payload); // Debug.Log($"Received message on topic '{topic}': {payload}"); // }); // try // { // await mqttClient.ConnectAsync(options, CancellationToken.None); // } // catch (Exception ex) // { // Debug.LogError($"Error connecting to MQTT broker: {ex.Message}"); // } //} //private async Task SubscribeToTopic(string topic) //{ // await mqttClient.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic(topic).Build()); // Debug.Log($"Subscribed to topic '{topic}'."); //} //private void HandleReceivedMessage(MqttApplicationMessageReceivedEventArgs e) //{ // string topic = e.ApplicationMessage.Topic; // string payload = Encoding.UTF8.GetString(e.ApplicationMessage.Payload); // Debug.Log($"Received message on topic '{topic}': {payload}"); //} //private async Task UnsubscribeFromTopic(string topic) //{ // await mqttClient.UnsubscribeAsync(topic); // Debug.Log($"Unsubscribed from topic '{topic}'."); //} //private async void OnDestroy() //{ // if (mqttClient != null && mqttClient.IsConnected) // { // await mqttClient.DisconnectAsync(); // Debug.Log("Disconnected from MQTT broker."); // } //} }