直接上代码:
第一步:使用NugGet 安装 M2Mqtt 工具,选择最新版本即可;
第二步:输入服务器的IP 及端口,创建客户端:
cs
MqttClient client;
public MqttApi()
{
// MQTT服务器IP地址
string host = "172.16.60.122";
int serverPort = 1883;
// 实例化Mqtt客户端
client = new MqttClient(host, Convert.ToInt32(serverPort), false, null, null, MqttSslProtocols.TLSv1_2);
}
第三步:设置主题,订阅主题,然后发送信息
cs
public void SendProgram()
{
// MQTT的主题 topic 设备类型
string topic = "/fac/sensor/data";
string clientId = Guid.NewGuid().ToString();
client.Connect(clientId, "admin", "admin123"); // 设置用户名和密码(如果需要)
// 订阅主题 "/mqtt/test", 订阅质量 QoS 2
client.Subscribe(new string[] { topic }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
// 发布消息
//var msg = "{\"deviceCode\":\"SM001\",\"Program\":{\"ProgramName\":\"ee\",\"WaferMappingFileName\":\"rr\"}}";
var msg = "{\"deviceCode\":\"SM001\",\"devicestatusInfo\":{\"description\":\"停止\",\"descriptioncode\":2,\"devicestatus\":1,\"preDeviceStatus\":\"\",\"preStatusStartTime\":\"\",\"remark\":\"\",\"statusStarTime\":1712651038054}}";
var res= client.Publish(topic, Encoding.UTF8.GetBytes(msg), MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE, false);
// 处理消息接收事件(现在 回复消息 可以不订阅这个主题)
client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;
}
public void Client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
{
string message = Encoding.UTF8.GetString(e.Message);
Console.WriteLine($"Mqtt Received: {message}");
}
完成。