在NuGet库里面直接查找M2Mqtt就可以安装库。
使用framework4.5.2
1.配置文件操作
public static class GModel
{
public static BassSetup MainSetup { get; set; }
public static void GetThisAdd()
{
MainSetup = new BassSetup();
string IPAdd = ConfigurationManager.AppSettings["IPAdd"];
string ServerPort = ConfigurationManager.AppSettings["ServerPort"];
string UserName = ConfigurationManager.AppSettings["UserName"];
string Pwd = ConfigurationManager.AppSettings["Pwd"];
MainSetup.IPAdd = IPAdd ;
MainSetup.ServerPort =int.Parse(ServerPort);
MainSetup.UserName = UserName;
MainSetup.Pwd = Pwd;
}
}
2连接服务器:
/// <summary>
/// 连接服务
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button4_Click(object sender, EventArgs e)
{
string EMQX_CLIENT_ID = Guid.NewGuid().ToString();
mqttClient = new MqttClient(GModel.MainSetup.IPAdd, GModel.MainSetup.ServerPort, false, null, null, MqttSslProtocols.None);
//mqttClient = new MqttClient("http://192.168.0.197:61613");此方法不妥
mqttClient.Connect(EMQX_CLIENT_ID,GModel.MainSetup.UserName,GModel.MainSetup.Pwd);//需要录入账号密码
mqttClient.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;//订阅后的动作
//mqttClient.Subscribe(new string[] { "123123124124512" }, new byte[] { MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE });
BTConnect.BackColor = Color.Green;
}
3.订阅后的事件
//这段定义了收到消息之后做什么事情
private void Client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
{
string topic = e.Topic.ToString();
string message = System.Text.Encoding.Default.GetString(e.Message);
//同时订阅两个或者以上主题时,分类收集收到的信息
//reciveTopic.Text = topic;
//reciveMessagetxt.Text = message;
}
4.订阅主题
/// <summary>
/// 订阅
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
if (mqttClient != null && !string.IsNullOrEmpty(TBZhuti.Text) )
{
mqttClient.Subscribe(new string[] { TBZhuti.Text}, new byte[] { MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE });//一次订阅多个主题似乎会出错
}
else
{
MessageBox.Show("请先连接服务器,并且确认订阅主题有数据。",this.Text,MessageBoxButtons.OK,MessageBoxIcon.Information);
}
}
5.发布主题。
/// <summary>
/// 发布
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
if (mqttClient != null && !string.IsNullOrEmpty(TBZhuti.Text) && !string.IsNullOrEmpty(RTBContent.Text))
{
mqttClient.Publish(TBZhuti.Text, System.Text.Encoding.UTF8.GetBytes(RTBContent.Text), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false);
}
}
6,解除订阅
/// <summary>
/// 解除订阅
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button3_Click(object sender, EventArgs e)
{
mqttClient.Unsubscribe(new string[] { "AAAAAA242" });
}
7.断开服务器连接
/// <summary>
/// 断开连接
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void DisConnect_Click(object sender, EventArgs e)
{
mqttClient.Disconnect();
}
https://github.com/eclipse/paho.mqtt.m2mqtt