[英]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.