标签:通讯 手机客户端 run odi 系统 扩展 address span 电量
老规矩,先简单介绍下MQTT:
MQTT(Message Queuing Telemetry Transport,消息队列遥测传输)是IBM开发的一个即时通讯协议,有可能成为物联网的重要组成部分。该协议支持所有平台,几乎可以把所有联网物品和外部连接起来,被用来当做传感器和致动器(比如通过Twitter让房屋联网)的通信协议,在未来几年,MQTT的应用会越来越广,值得关注。
很显然,UWP也是有MQTT的,要使用它需要安装M2Mqtt这个Nuget包。引用
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;
Mqtt的使用非常简单,首先new 一个MqttClient,然后Connect,Subscribe订阅消息,此时就可以接受到你订阅的房间的消息了,可以通过Publish发布消息.
下面是具体实现:
public void ConnMqtt() { string mqtthost = "your ip address"; int mqttport = your port; string mqttServer = "your server"; mc.Connect(mqttServer); //mc = new MqttClient(mqtthost,mqttport,false, MqttSslProtocols.None); mc.MqttMsgPublishReceived += Mc_MqttMsgPublishReceived; try { string clientId = Guid.NewGuid().ToString(); mc.Connect(clientId); //mc.Connect(clientId,"username","password"); } catch(Exception ex) { Debug.WriteLine(ex.Message); } SubscribeMqtt(new[] { "test" }); //订阅 } public void SubscribeMqtt(string[] topics) //订阅 { mc.Subscribe(topics, new[] { MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE }); } public void PublishMqtt(string topic, string message) //发布,发布时自己也能收到消息 { var v = mc.Publish(topic, Encoding.UTF8.GetBytes(message), MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE, true); } async private void Mc_MqttMsgPublishReceived(object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPublishEventArgs e) { var msg = Encoding.UTF8.GetString(e.Message); await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { ReciveTextBox.Text += msg + "\r\n"; }); }
标签:通讯 手机客户端 run odi 系统 扩展 address span 电量
原文地址:http://www.cnblogs.com/Yixin-ran/p/mqtt.html