前面使用的RabbitMQ 的MQTT服务,但我们使用MQTTnet 也是可以自己开发出一个服务端的
GitHub - harrylsp/MQTTServer: MQTTServerMQTTServer. Contribute to harrylsp/MQTTServer development by creating an account on GitHub.https://github.com/harrylsp/MQTTServer
1.安装MQTTnet库 2.创建MQTT服务 2.1 创建服务对象public MqttServer mqttServer = null; mqttServer = new MqttFactory().CreateMqttServer() as MqttServer;2.2 创建服务对象参数配置
var optionsBuilder = new MqttServerOptionsBuilder()
.WithDefaultEndpoint().WithDefaultEndpointPort(1883).WithConnectionValidator(c =>
{
var currentUser = username;
var currentPwd = password;
if (currentUser == null || currentPwd == null)
{
c.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
return;
}
if (c.Username != currentUser || c.Password != currentPwd)
{
c.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
}
c.ReasonCode = MqttConnectReasonCode.Success;
})
.WithSubscriptionInterceptor(c =>
{
c.AcceptSubscription = true;
})
.WithApplicationMessageInterceptor(c =>
{
c.AcceptPublish = true;
});
2.3 注册监听回调事件
mqttServer.StartedHandler = new MqttServerStartedHandlerDelegate(new Action2.4 开始启动服务对象(e => { if (mqttServer.IsStarted) { } LogManager.WriteLogEx(LOGLEVEL.INFO, "MQTT服务启动完成!"); })); mqttServer.StoppedHandler = new MqttServerStoppedHandlerDelegate(new Action (e => { if (!mqttServer.IsStarted) { } LogManager.WriteLogEx(LOGLEVEL.INFO, "MQTT服务停止完成!"); })); mqttServer.ClientConnectedHandler = new MqttServerClientConnectedHandlerDelegate(new Action (e => { LogManager.WriteLogEx(LOGLEVEL.INFO, $"客户端[{e.ClientId}]已连接"); })); mqttServer.ClientDisconnectedHandler = new MqttServerClientDisconnectedHandlerDelegate(new Action (e => { LogManager.WriteLogEx(LOGLEVEL.INFO, $"客户端[{e.ClientId}]已断开连接!"); })); mqttServer.ClientSubscribedTopicHandler = new MqttServerClientSubscribedTopicHandlerDelegate(new Action (e => { LogManager.WriteLogEx(LOGLEVEL.INFO, $"客户端[{e.ClientId}]已成功订阅主题[{e.TopicFilter}]!"); })); mqttServer.ClientUnsubscribedTopicHandler = new MqttServerClientUnsubscribedTopicHandlerDelegate(new Action (e => { LogManager.WriteLogEx(LOGLEVEL.INFO, $"客户端[{e.ClientId}]已成功取消订阅主题[{e.TopicFilter}]!"); })); mqttServer.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(new Action (e => { LogManager.WriteLogEx(LOGLEVEL.INFO, $"客户端[{e.ClientId}]>> 主题:{e.ApplicationMessage.Topic} 负荷:{Encoding.UTF8.GetString(e.ApplicationMessage.Payload)} Qos:{e.ApplicationMessage.QualityOfServiceLevel} 保留:{e.ApplicationMessage.Retain}"); }));
await mqttServer.StartAsync(optionsBuilder.Build());2.5 服务运行 2.6 测试连接 3. 发布消息
var message = new MqttApplicationMessage()
{
Topic = topic,
Payload = Encoding.UTF8.GetBytes(payload)
};
await mqttServer.PublishAsync(message);
4. 其他
源代码:GitHub - harrylsp/MQTTServer: MQTTServer
更专业的MQTT服务 EMQX
https://www.emqx.com/zh/downloads-and-install?product=broker&version=4.3.10&os=Windows&oslabel=Windows



