mqtt向android推送消息(一)——发送端使用.net

 

使用.net进行mqtt协议通讯,主要是为了开发居于mqtt协议向android推送消息,使用.net开发可以参考mqtt.org上面的库,我用的是M2MQTT,网上资料很少,具体例子如下:
一、消息发布:
if (this.sender == null)
            {
                this.sender = new MqttClient(IPAddress.Parse(host), 1883);
                //var mqttClient = new MqttClient("localhost");
                this.sender.Connect("sender");
            }
            this.sender.Publish("mobileGKTopic", System.Text.Encoding.Default.GetBytes(textBox2.Text));
 二、消息接收
 mqttClient = new MqttClient(IPAddress.Parse(host), 1883);
            //mqttClient = new MqttClient("localhost");
            mqttClient.Connect("Receiver");
            mqttClient.MqttMsgPublishReceived += new MqttClient.MqttMsgPublishEventHandler(mqttClient_MqttMsgPublishReceived);

            

            mqttClient.Subscribe(new string[] { "testTopic" }, new byte[] { MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE });

private void mqttClient_MqttMsgPublishReceived(object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPublishEventArgs e)
        {
            //throw new NotImplementedException();
            var msg = System.Text.Encoding.Default.GetString(e.Message);
            if (!String.IsNullOrEmpty(msg))
            {
                textBox1.AppendText(Environment.NewLine);
                textBox1.AppendText(msg);
            }
        }
 需要注意的是,编译mqtt库时要把条件编译SSL关闭,SSL的编译我还没有高清。

mqtt向android推送消息(一)——发送端使用.net_第1张图片
 

你可能感兴趣的:(android,.net,C#)