[英]M2mqtt Subscribing to topic using string variable
client.Subscribe(new string[] { "hello/world" }, new byte[] {MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
我正在測試上述內容,它工作得很好。 但是...當我嘗試以下操作時,我的代碼根本不起作用,也不會引發任何異常。
string variable = "hello/world";
client.Subscribe(new string[] { variable }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
我已經嘗試過:
string variable = "hello/world";
string[] stringArray = new string[] { variable };
client.Subscribe(stringArray, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
還:
string variable = "hello/world";
client.Subscribe(new []{ variable }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
我怎樣才能讓它正常工作?
謝謝!
@edit:服務器端日志:
Server auth 2b6240f1-593a-4217-b3d5-ae8c666099ca from 127.0.0.1
Client 2b6240f1-593a-4217-b3d5-ae8c666099ca connected
Total connections: 3
$SYS/LIZO1uD/new/clients 2b6240f1-593a-4217-b3d5-ae8c666099ca
當客戶端連接並訂閱時:
Server auth 6ba2d202-f595-4e37-a1d4-8ae6b134a370 from 127.0.0.1
Client 6ba2d202-f595-4e37-a1d4-8ae6b134a370 connected
Total connections: 3
$SYS/LIZO1uD/new/clients 6ba2d202-f595-4e37-a1d4-8ae6b134a370
$SYS/LIZO1uD/new/subscribes {"clientId":"6ba2d202-f595-4e37-a1d4-8ae6b134a370","topic":"hello/world"}
我已經整理了一個快速工作的例子。 試試看你是否得到任何結果。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;
namespace MqttApp
{
class Program
{
static void Main(string[] args)
{
string BrokerAdress = "mqtt.server.local";
string ClientID = "CSharpMqttClient";
string Topic = "hello/world";
string MessageToPublish;
//Create MQTT client instance
MqttClient mqttClient = new MqttClient(BrokerAdress);
Console.WriteLine("mqttClient instaceed for broker " + BrokerAdress);
// register to message received
mqttClient.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
//Subscribe to the indicated topic
// subscribe to the topic with QoS 2
mqttClient.Subscribe(new string[] {Topic}, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
//Connect mqttCient
mqttClient.Connect(ClientID,"","",true,60);
Console.WriteLine(ClientID + " connected");
// publish messages on "hello world" topic with QoS 2
MessageToPublish = "hello world";
mqttClient.Publish(Topic, Encoding.UTF8.GetBytes(MessageToPublish), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false);
System.Console.WriteLine("Published message: " + MessageToPublish);
}
static void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
{
// handle message received
var msg = System.Text.Encoding.Default.GetString(e.Message);
System.Console.WriteLine("Message Received: " + msg);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.