客户端基
/// <summary>
///
/// </summary>
public class BaseClient : IDisposable
{
protected string client;
protected int port;
protected string username;
protected string password;
protected IMqttClient mqttClient;
protected bool needPassword = false;
public BaseClient(string client, int port = 1883)
{
this.client = client;
this.port = port;
}
public BaseClient(string client, int port = 1883, string username = "admin", string password = "public")
{
this.client = client;
this.port = port;
this.username = username;
this.password = password;
needPassword = true;
}
public BaseClient Connect()
{
MqttFactory mqttFactory = new MqttFactory();
mqttClient = mqttFactory.CreateMqttClient();
MqttClientOptions mqttClientOptions = new MqttClientOptionsBuilder()
.WithTcpServer(client, port)
.Build();
if (needPassword)
{
mqttClientOptions.Credentials = new MqttClientCredentials(username, Encoding.Default.GetBytes(password));
}
mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None).Wait();
return this;
}
public void DisConnect()
{
mqttClient.DisconnectAsync().Wait();
}
public void Dispose()
{
if (mqttClient == null)
{
return;
}
if (mqttClient.IsConnected)
{
mqttClient.DisconnectAsync().Wait();
}
mqttClient.Dispose();
}
}
消费者
public class MQTTClientSubscribe : BaseClient, IDisposable
{
MqttFactory mqttFactory = new MqttFactory();
public MQTTClientSubscribe(string client, int port = 1883, string username = "admin", string password = "public") : base(client, port, username, password)
{
}
public MQTTClientSubscribe(string server, int port = 1883) : base(server, port)
{
}
public void InvokeReceived(Action action)
{
mqttClient.ApplicationMessageReceivedAsync += e =>
{
System.Console.WriteLine("Received application message:" + e.ApplicationMessage.ConvertPayloadToString());
e.DumpToConsole();
e.ApplicationMessage.ConvertPayloadToString();
action?.Invoke();
return Task.CompletedTask;
};
}
public void SubscribeTopic(string topic)
{
MqttClientSubscribeOptions mqttSubscribeOptions = mqttFactory.CreateSubscribeOptionsBuilder()
.WithTopicFilter(f => { f.WithTopic(topic); })
.Build();
mqttClient.SubscribeAsync(mqttSubscribeOptions, CancellationToken.None).Wait();
}
}
生产者
public class MQTTClientPublish : BaseClient, IDisposable
{
public MQTTClientPublish(string client, int port = 1883) : base(client, port)
{
}
public MQTTClientPublish(string client, int port = 1883, string username = "admin", string password = "public") : base(client, port, username, password)
{
}
/// <summary>
/// 发送数据
/// </summary>
/// <param name="topic"></param>
/// <param name="data"></param>
/// <returns></returns>
public void PublishMessage(string topic, string data)
{
MqttApplicationMessage applicationMessage = new MqttApplicationMessageBuilder()
.WithTopic(topic)
.WithPayload(data)
.Build();
mqttClient.PublishAsync(applicationMessage, CancellationToken.None).Wait();
}
}