【发布时间】:2017-03-22 07:26:35
【问题描述】:
我无法使用 mqtt 将 wpf 转换为 asp.net。我的代码没有显示任何错误,但是当我启动并输入一些文本并单击按钮时,它会显示一个错误 "在 WebApplication4.dll 中发生了 'System.NullReferenceException' 类型的异常,但未在用户代码中处理"
public partial class Testing : System.Web.UI.Page
{
MqttClient client;
string clientId;
protected void Page_Load(object sender, EventArgs e)
{
}
public void MainWindow()
{
string BrokerAddress = "test.mosquitto.org";
client = new MqttClient(BrokerAddress);
// register a callback-function (we have to implement, see below) which is called by the library when a message was received
client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
// use a unique id as client id, each time we start the application
clientId = Guid.NewGuid().ToString();
client.Connect(clientId);
}
void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
{
string ReceivedMessage = Encoding.UTF8.GetString(e.Message);
txtReceived.Text = ReceivedMessage;
}
protected void btnPublish_Click(object sender, EventArgs e)
{
if (txtTopicPublish.Text != "")
{
// whole topic
string Topic = "" + txtTopicPublish.Text + "";
// publish a message with QoS 2
client.Publish(Topic, Encoding.UTF8.GetBytes(txtPublish.Text), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, true);
}
else
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "Scripts", "<script>alert('You have to enter a topic to publish!')</script>");
}
}
【问题讨论】:
-
这是“我的代码不起作用,请为我修复”的问题之一。您可以通过在提出问题之前表明您已努力解决问题来避免投反对票。
-
client在哪里定义?你为什么要从txtTopicPublish.Text组成一个字符串Topic而从不使用它?为什么在测试txtTopicPublish.Textisn'tpy 时使用txtPublish.Text? -
@Heki 好吧,它适用于我的 wpf,我只尝试将其转换为 asp.net,我尝试了但找不到代码
-
当
btnPublish_Click被调用时,我愿意打赌client是null。对吗?