我无法使用mqtt将wpf转换为asp.net。我的代码没有显示任何错误,但是当我启动并输入一些文本和单击按钮时,它将显示错误 "类型' System.NullReferenceException'的例外;发生在WebApplication4.dll中但未在用户代码"
中处理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>");
}
}
答案 0 :(得分:0)
似乎缺乏对ASP.NET page lifecycle的理解。
在WPF中,生命周期从运行程序到关闭时为止。它是有状态的。 ASP.NET不是;无论你在Page_Load
(以及其他生命周期事件)中做什么,都会在完成呈现页面时处理。
您有几种方法可以解决您的问题。
MqttClient
实例保留在Application
对象中。这使得实例在AppPool启动时保持活动状态(在Application_Start
中的Global.asax
事件中实例化客户端。它在AppPool启动时被触发)直到它关闭(Application_End
,其中如果你想要/需要,你有机会优雅地关闭MqttClient
。它由所有用户共享,可以Application[key]
随处访问,其中key
是任意字符串,例如"MqttClient"
。Session
对象中,方法与Application
对象相同。您可以以相同的方式使用Sesson_Start
和Session_End
。 Session
对象对于每个用户都是唯一的,就其保持活跃状态而言,直到用户停止浏览您的网站为止。MqttClient
时实例化Page_Load
。