一,什么是MQTT:
MQTT(消息队列遥测传输)是IBM开发的即时通讯协议,是一个基于服务器的消息发布/订阅极其轻量级的消息传输协议。
它工作在 TCP/IP协议族上,专门为网络受限设备、低宽带以及高延迟和不可靠的网络而设计的(传输特点:至多一次、至少一次、只有一次)。使其在物联网、小型设备、移动应用等方面有较广泛的应用。
1.MQTT报文:
详情见:https://www.cnblogs.com/hayasi/p/7743356.html
2.MQTT三种身份:发布者(客户端)、代理(服务器)、订阅者(客户端)。
二,示例
可以选择MQTTnet包或者DotNetty.Codecs.Mqtt包进行学习,这里我们选用Mqtt进行学习。
VS2019
Net5
MQTTnet 3.1.2
1.服务端(WinForm):
①服务器对象初始化(new MqttServerFactory().CreateMqttServer(new MqttServerOptionsBuilder().Build());)
补充:
a. MqttServerOptionsBuilder的属性
| 函数名 | 功能说明 |
| Build() | 构建配置参数 |
| WithApplicationMessageInterceptor() | 允许处理来自客户端的所有已发布消息 |
| WithClientId() | 服务端发布消息时使用的ClientId |
| WithConnectionBacklog() | 设置要保留的连接数 |
| WithConnectionValidator() | 验证连接 |
| WithDefaultCommunicationTimeout() | 设置默认的通信超时 |
| WithDefaultEndpoint() | 使用默认端点 |
| WithDefaultEndpointBoundIPAddress() | 使用默认端点IPv4地址 |
| WithDefaultEndpointBoundIPV6Address() | 使用默认端点IPv6地址 |
| WithDefaultEndpointPort() | 使用默认端点端口 |
| WithEncryptedEndpoint() | 使用加密的端点 |
| WithEncryptedEndpointBoundIPAddress() | 使用加密的端点IPv4地址 |
| WithEncryptedEndpointBoundIPV6Address() | 使用加密的端点IPv6地址 |
| WithEncryptedEndpointPort() | 使用加密的端点端口 |
| WithEncryptionCertificate() | 使用证书进行SSL连接 |
| WithEncryptionSslProtocol() | 使用SSL协议级别 |
| WithMaxPendingMessagesPerClient() | 每个客户端允许最多未决消息 |
| WithPersistentSessions() | 保持会话 |
| WithStorage() | 使用存储 |
| WithSubscriptionInterceptor() | 允许处理来自客户端的所有订阅 |
| WithoutDefaultEndpoint() | 禁用默认端点 |
| WithoutEncryptedEndpoint() | 禁用默认(SSL)端点 |
②服务器启动(await mqttServer.StartAsync())
③是否对客户端的进行验证(账号密码)
④客户端订阅/取消订阅事件
⑤接收客户端数据(ApplicationMessageReceived)
⑥给客户端发送数据
⑦客户端连接(ClientConnected)
⑧客户端断开连接(ClientDisconnected)
⑨日志消息(MqttNetTrace )
2.客户端(WinForm):
客户端对象初始化()
客户端对象启动()
④客户端订阅/取消订阅事件(mqttClient.SubscribeAsync()与mqttClient.PublishAsync(appMsg))
连接服务端(Connected)
断开服务端(Disconnected)
接受服务器的数据(ApplicationMessageReceived)
给服务器发送数据()
日志消息(MqttNetTrace)
3.补充-服务端(NetCore):
参考:
https://www.cnblogs.com/hayasi/p/7743356.html
https://www.cnblogs.com/dathlin/p/11631894.html
https://www.cnblogs.com/sxkgeek/p/9140180.html
https://www.shangmayuan.com/a/67b2f4a9f2c440e9b2db3a97.html
https://zhuanlan.zhihu.com/p/419561816
https://blog.csdn.net/qq_37258787/article/details/80183923
https://www.cnblogs.com/dathlin/p/11631894.html
https://www.jianshu.com/p/a371c6ac076b