引言
本段代码的含义在之前的一篇文章里有介绍,本文为完整代码的展示,之前介绍用的文章,点击此处即可查看
Demo代码:
using System;
using System.Net;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;
using System.Windows.Forms;
using System.Security.Cryptography;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
//阿里云的数据
static string ProductKey = "***";//输入自己的ProductKey
static string DeviceName = "***";//输入自己的DeviceName
static string DeviceSecret = "***";//输入自己的DeviceSecret
static string RegionId = "cn-shanghai";
static string PubTopic = "/" + ProductKey + "/" + DeviceName + "/user/update";
static string SubTopic = "/" + ProductKey + "/" + DeviceName + "/user/get";
public Form1()
{
InitializeComponent();
System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
}
private void label1_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
label3.Text = "数据已经上传!";
//开始连接阿里云
IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
string clientId = host.AddressList.FirstOrDefault(
ip => ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).ToString();
string t = Convert.ToString(DateTimeOffset.Now.ToUnixTimeMilliseconds());
string signmethod = "hmacmd5";
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("productKey", ProductKey);
dict.Add("deviceName", DeviceName);
dict.Add("clientId", clientId);
dict.Add("timestamp", t);
string mqttUserName = DeviceName + "&" + ProductKey;
string mqttPassword = IotSignUtils.sign(dict, DeviceSecret, signmethod);
string mqttClientId = clientId + "|securemode=3,signmethod=" + signmethod + ",timestamp=" + t + "|";
string targetServer = ProductKey + ".iot-as-mqtt." + RegionId + ".aliyuncs.com";
ConnectMqtt(targetServer, mqttClientId, mqttUserName, mqttPassword);
}
public void ConnectMqtt(string targetServer, string mqttClientId, string mqttUserName, string mqttPassword)
{
MqttClient client = new MqttClient(targetServer);
client.ProtocolVersion = MqttProtocolVersion.Version_3_1_1;
client.Connect(mqttClientId, mqttUserName, mqttPassword, false, 60);
client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;
//订阅消息
client.Subscribe(new string[] { SubTopic }, new byte[] { 0 });
//发布消息,发布的消息为我们在textBox1上的Text
String content = textBox1.Text;
//他上传的数据需要时byte[],所以我们先需要将string类转换成byte[]
byte[] by1 = System.Text.Encoding.ASCII.GetBytes(content);
var id = client.Publish(PubTopic, by1);
}
public void Client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
{
//对获得的message的处理
string topic = e.Topic;
string message = Encoding.ASCII.GetString(e.Message);//从被订阅端获取消息
int length = message.Length;//我们先得到这条message的长度,
//因为是string所以调用他的length函数就可以了
label2.Text = message.Substring(0, length);//label3原先是null,
//后来就会变成message的内容,从头开始读,长度就是length
}
}
public class IotSignUtils//签名文件
{
public static string sign(Dictionary<string, string> param,
string deviceSecret, string signMethod)
{
string[] sortedKey = param.Keys.ToArray();
Array.Sort(sortedKey);
StringBuilder builder = new StringBuilder();
foreach (var i in sortedKey)
{
builder.Append(i).Append(param[i]);
}
byte[] key = Encoding.UTF8.GetBytes(deviceSecret);
byte[] signContent = Encoding.UTF8.GetBytes(builder.ToString());
//这里根据signMethod对代码进行了一些动态调整,于是写了一个HMACMD5
var hmac = new HMACMD5(key);
byte[] hashBytes = hmac.ComputeHash(signContent);
StringBuilder signBuilder = new StringBuilder();
foreach (byte b in hashBytes)
signBuilder.AppendFormat("{0:x2}", b);
return signBuilder.ToString();
}
}
}