private void MqttClient_Disconnected(object sender, EventArgs e) { Application.Current.Dispatcher.Invoke((new Action(() => { MQTT.AppendText("已断开MQTT连接!" + Environment.NewLine); }))); }
private async Task ConnectMqttServerAsync() { if (mqttClient == null) { mqttClient = new MqttClientFactory().CreateMqttClient() as MqttClient; mqttClient.ApplicationMessageReceived += MqttClient_ApplicationMessageReceived; mqttClient.Connected += MqttClient_Connected; mqttClient.Disconnected += MqttClient_Disconnected; } try { var options = new MqttClientTcpOptions { Server = "127.0.0.1", ClientId = "win7-PC", UserName = "******", Password = "******", CleanSession = true }; await mqttClient.ConnectAsync(options); } catch (Exception ex) { Application.Current.Dispatcher.Invoke((new Action(() => { MQTT.AppendText($"连接到MQTT服务器失败!" + Environment.NewLine + ex.Message + Environment.NewLine); }))); } }
private void MqttClient_Connected(object sender, EventArgs e) { Application.Current.Dispatcher.Invoke((new Action(() => { MQTT.AppendText("已连接到MQTT服务器!" + Environment.NewLine); }))); string topic = "/ros_planned_path"; if (!mqttClient.IsConnected) { MessageBox.Show("MQTT客户端尚未连接!"); return; } mqttClient.SubscribeAsync(new List <TopicFilter> { new TopicFilter(topic, MqttQualityOfServiceLevel.AtMostOnce) }); Application.Current.Dispatcher.Invoke(new Action(() => { MQTT.AppendText($"已订阅[{topic}]主题" + Environment.NewLine); })); }