发送消息
- 引用的MQTTnet最新4.1.0版本,新增MqttClientService类,实例化client。然后连接到服务端后向指定topic发送消息
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Protocol;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace MQTTPublish
{
public class MqttClientService
{
public static IMqttClient _mqttClient;
public IMqttClient MqttClientStart(string ip, int port, string username, string pwd, string clientId)
{
var optionsBuilder = new MqttClientOptionsBuilder()
.WithTcpServer(ip, port) // 要访问的mqtt服务端的 ip 和 端口号
.WithCredentials(username, pwd) // 要访问的mqtt服务端的用户名和密码
.WithClientId(clientId) // 设置客户端id
.WithCleanSession()
.WithTls(new MqttClientOptionsBuilderTlsParameters
{
UseTls = false // 是否使用 tls加密
});
var clientOptions = optionsBuilder.Build();
_mqttClient = new MqttFactory().CreateMqttClient();
//_mqttClient.ConnectedAsync += _mqttClient_ConnectedAsync; // 客户端连接成功事件
//_mqttClient.DisconnectedAsync += _mqttClient_DisconnectedAsync; // 客户端连接关闭事件
//_mqttClient.ApplicationMessageReceivedAsync += _mqttClient_ApplicationMessageReceivedAsync; // 收到消息事件
_mqttClient.ConnectAsync(clientOptions);
return _mqttClient;
}
}
}
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Protocol;
using MQTTnet.Server;
using System;
using System.Text;
using System.Threading.Tasks;
namespace MQTTPublish
{
internal class Program
{
private static IMqttClient client;
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
client = new MqttClientService().MqttClientStart("127.0.0.1", 1883, "cyw", "123456", "cywcyw");
client.ConnectedAsync += Client_ConnectedAsync;
Console.ReadLine();
}
private static System.Threading.Tasks.Task Client_ConnectedAsync(MqttClientConnectedEventArgs arg)
{
Console.WriteLine("Client_ConnectedAsync");
var message = new MqttApplicationMessage
{
Topic = "test",
Payload = Encoding.Default.GetBytes("cyw-123456"),
QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce,
Retain = true // 服务端是否保留消息。true为保留,如果有新的订阅者连接,就会立马收到该消息。
};
Console.WriteLine("PublishAsync topic:"+ message.Topic+ " Payload:"+ Encoding.UTF8.GetString(message.Payload));
client.PublishAsync(message);
return Task.CompletedTask;
}
}
}