Files
TouchSocket/handbook/docs/mqttservice.mdx
2025-06-25 23:17:46 +08:00

85 lines
2.4 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
id: mqttservice
title: Mqtt服务器
---
import Tag from "@site/src/components/Tag.js";
### 定义
命名空间TouchSocket.Mqtt <br/>
程序集:[TouchSocket.Mqtt.dll](https://www.nuget.org/packages/TouchSocket.Mqtt)
## 一、说明
`MqttTcpService` 是基于 Mqtt 协议的消息服务端,支持客户端接入管理、订阅关系维护、消息路由转发、遗嘱消息处理等功能,兼容 Mqtt 3.1.1 及 5.0+ 协议版本。
## 二、特点
- 多协议版本支持v3.1.1/v5.0
- 高性能异步架构设计
- 主题树形管理机制
- 精确的 QoS 保障
- 遗嘱消息转发
- 插件化扩展体系
- TLS 加密通信
- 客户端黑白名单控制
## 三、应用场景
- 工业物联网平台
- 实时数据监控中心
- 智慧城市中枢系统
- 私有化消息总线
- 设备远程管理服务
## 四、可配置项
继承所有 [TcpService](./tcpservice.mdx) 的配置。除此之外还支持 Mqtt 服务端专有配置。
<details>
<summary>可配置项</summary>
<div>
</div>
</details>
## 五、支持插件
| 插件方法| 功能 |
| --- | --- |
| IMqttConnectingPlugin | 当Mqtt客户端正在连接之前调用此方法。 |
| IMqttConnectedPlugin | 当Mqtt客户端连接成功时调用。 |
| IMqttClosingPlugin | 当Mqtt客户端正在关闭时调用。|
| IMqttClosedPlugin | 当Mqtt客户端断开连接后触发。 |
| IMqttReceivingPlugin | 在收到Mqtt所有消息时触发可以通过`e.MqttMessage`获取到`Mqtt`的所有消息,包括订阅、订阅确认、发布、发布确认等。 |
| IMqttReceivedPlugin | 当接收到Mqtt发布消息且成功接收时触发。可以通过`e.MqttMessage`获取到`Mqtt`的发布消息。 |
## 六、创建Mqtt服务端
```csharp showLineNumbers
var service = new MqttTcpService();
await service.SetupAsync(new TouchSocketConfig()
.SetListenIPHosts(7789) // 监听所有网卡
.ConfigureContainer(a =>
{
a.AddConsoleLogger();
})
.ConfigurePlugins(a =>
{
a.AddMqttClientConnectedPlugin(async (service, e) =>
{
Console.WriteLine($"Client Connected:{e.ClientId}");
await e.InvokeNext();
});
a.AddMqttClientDisconnectedPlugin(async (service, e) =>
{
Console.WriteLine($"Client Disconnected:{e.ClientId}");
await e.InvokeNext();
});
}));
await service.StartAsync();
```