Mqtt和asp.net Web应用程序,需要帮助

时间:2017-03-22 07:26:36

标签: c# asp.net wpf mqtt

我无法使用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>");
                }
            } 

1 个答案:

答案 0 :(得分:0)

似乎缺乏对ASP.NET page lifecycle的理解。 在WPF中,生命周期从运行程序到关闭时为止。它是有状态的。 ASP.NET不是;无论你在Page_Load(以及其他生命周期事件)中做什么,都会在完成呈现页面时处理。

您有几种方法可以解决您的问题。

  1. 您可以将MqttClient实例保留在Application对象中。这使得实例在AppPool启动时保持活动状态(在Application_Start中的Global.asax事件中实例化客户端。它在AppPool启动时被触发)直到它关闭(Application_End,其中如果你想要/需要,你有机会优雅地关闭MqttClient。它由所有用户共享,可以Application[key]随处访问,其中key是任意字符串,例如"MqttClient"
  2. 您可以将其保存在Session对象中,方法与Application对象相同。您可以以相同的方式使用Sesson_StartSession_EndSession对象对于每个用户都是唯一的,就其保持活跃状态​​而言,直到用户停止浏览您的网站为止。
  3. 您可以在每次需要时或MqttClient时实例化Page_Load