C# 利用M2Mqtt库开发MQTT通信协议
直接上代码:第一步:利用NugGet 安装 M2Mqtt 工具,选择最新版本即可;
第二步:输入服务器的IP 及端口,创建客户端:
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);
} 第三步:设置主题,订阅主题,然后发送信息
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}");
} 完成。
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页:
[1]