MQTT测试程序连接秒断
问题描述
使用MQTT测试程序MQTTX连接服务器,点击连接后直接断开,或者无限重新连接。
解决方式
方式1: 切换协议,试试MQTT 3.0,MQTT 3.1.1,MQTT 5.0,看看那个可行就用那个,或者问问服务器方使用的MQTT服务器的版本,客户端的版本需要和服务器端的版本保持一致。
方式2:检查测试程序的Clean Session,设置为true试试再试试false
MQTT连接测试程序可以连接代码无法连接
以下的代码是基于BestMQTT和BestMQTT实现的。
问题描述
使用MQTTX或者MQTTFX可以连接到MQTT服务器并发送数据,使用自己写的代码不能发送到服务器。
解决方式
方式1: 设置MQTT连级对象的Session
,再MQTT测试工具中的位置
方式二:强制指定MQTT客户端的版本
var c = new ConnectionOptionsBuilder()
.WithTCP(hostName, port)
.WithProtocolVersion(SupportedProtocolVersions.MQTT_3_1_1);
public enum SupportedProtocolVersions
{
MQTT_3_1_1,
MQTT_5_0
}
Best MQTT发送数据提示版本不一致
问题描述
使用BestMQTT发送数据的时候,提示
{
"tid": 1,
"div": "MQTTClient",
"msg": "OnConnected",
"ex": [{
"msg": "WithContentType is available with MQTT v5.0 or newer."
}]
}
版本过高,服务器的是MQTT3.1.1 但是使用的发送数据是的5.0的方式
//5.0的发送方式
//发送数据
client.CreateApplicationMessageBuilder(SendTopic)
.WithPayload(Message)
.WithQoS(QoSLevels.ExactlyOnceDelivery)
.WithContentType("text/plain; charset=UTF-8")
.BeginPublish();
//3.1.1的发送方式
client.CreateApplicationMessageBuilder(SendTopic)
.WithPayload(Message)
.BeginPublish();
BestMQTT 连接的全部代码
代码中包括:
- 使用MQTT 3.1.1发送数据,使用MQTT 5.0发送数据,
- 使用MQTT 3.1.1断开连接,使用MQTT 5.0断开连接,
- 订阅
- 设置Session
- 设置连接的用户名密码Clientid
- 连接中的事件以及连接中的连接状态的改变
Best MQTT文档
https://bestdocshub.pages.dev/MQTT/
https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901100
连接代码需要有BEST MQTT ,BEST HTTP
using BestMQTT;
using BestMQTT.Packets;
using BestMQTT.Packets.Builders;
using System;
using System.Text;
using UnityEngine;
public class myMqttOetTest : MonoBehaviour
{
private string hostName = "com";
private int port = 1883;
private string userName = "L24";//用户名
private string psd = "ver3D";//密码
private string clientId = "lind1";//客户端ID
private string Telling = "Telling";//标识符
private string Message = "Form C#";
private string SendTopic = "";//发送消息的Topic
private string GetTopic = "";//订阅的Topic
private MQTTClient client;
// Start is called before the first frame update
void Start()
{
var c = new ConnectionOptionsBuilder()
.WithTCP(hostName, port)
.WithProtocolVersion(SupportedProtocolVersions.MQTT_3_1_1);
client = new MQTTClientBuilder()
.WithOptions(c)
.WithEventHandler(OnConnected)
.WithEventHandler(OnDisconnected)
.WithEventHandler(OnStateChanged)
.WithEventHandler(OnError)
.CreateClient();
client.BeginConnect(ConnectPacketBuilderCallback);
}
private void OnConnected(MQTTClient client)
{
//订阅主题1
client.CreateSubscriptionBuilder(GetTopic)
.WithMessageCallback(OnMessage)
.WithAcknowledgementCallback(OnSubscriptionAcknowledged)
.WithMaximumQoS(QoSLevels.ExactlyOnceDelivery)
.BeginSubscribe();
//订阅主题2
//client.CreateSubscriptionBuilder("")
// .WithMessageCallback(OnMessage)
// .WithAcknowledgementCallback(OnSubscriptionAcknowledged)
// .WithMaximumQoS(QoSLevels.ExactlyOnceDelivery)
// .BeginSubscribe();
//5.0的发送数据
client.CreateApplicationMessageBuilder(SendTopic)
.WithPayload(Message)
.WithQoS(QoSLevels.ExactlyOnceDelivery)
.WithContentType("text/plain; charset=UTF-8")
.BeginPublish();
//3.0的发送数据
//client.CreateApplicationMessageBuilder(SendTopic)
// .WithPayload(Message)
// .BeginPublish();
}
private void OnMessage(MQTTClient client, SubscriptionTopic topic, string topicName, ApplicationMessage message)
{
// Convert the raw payload to a string
var payload = Encoding.UTF8.GetString(message.Payload.Data, message.Payload.Offset, message.Payload.Count);
Debug.Log($"收到消息:Content-Type: '{message.ContentType}' Payload: '{payload}'");
//取消订阅
//client.CreateUnsubscribePacketBuilder("best_mqtt/test_topic")
// .WithAcknowledgementCallback((client, topicFilter, reasonCode) => Debug.Log($"Unsubscribe request to topic filter '{topicFilter}' returned with code: {reasonCode}"))
// .BeginUnsubscribe();
}
/// <summary>
/// 在 MQTT 客户端订阅一个主题后接收到服务器的确认响应时被调用。
/// </summary>
/// <param name="client">MQTT 客户端对象</param>
/// <param name="topic"> 代表已订阅的主题的信息对象</param>
/// <param name="reasonCode">服务器返回的订阅确认码,表示订阅请求的结果</param>
private void OnSubscriptionAcknowledged(MQTTClient client, SubscriptionTopic topic, SubscribeAckReasonCodes reasonCode)
{
if (reasonCode <= SubscribeAckReasonCodes.GrantedQoS2)
{
//订阅成功
Debug.Log($"订阅成功。Successfully subscribed with topic filter '{topic.Filter.OriginalFilter}'. QoS granted by the server: {reasonCode}");
}
else
{
Debug.Log($"订阅失败:Could not subscribe with topic filter '{topic.Filter.OriginalFilter}'! Error code: {reasonCode}");
}
}
private void OnDestroy()
{
if (client != null)
{
//5.0的断开连接
//DisconnectPacketBuilder disconnectPacketBuilder = client.CreateDisconnectPacketBuilder();//创建一个用于构建断开连接请求的构建器对象。
//disconnectPacketBuilder.WithReasonCode(DisconnectReasonCodes.NormalDisconnection);//设置断开连接的原因代码为 NormalDisconnection,表示这是一个正常的断开连接请求。
//disconnectPacketBuilder.WithReasonString("Bye");//设置断开连接的原因字符串为 "Bye",这个字符串可以提供额外的描述信息,说明为什么断开连接。
//disconnectPacketBuilder.BeginDisconnect();
//3.0的断开连接
DisconnectPacketBuilder disconnectPacketBuilder = client.CreateDisconnectPacketBuilder();//创建一个用于构建断开连接请求的构建器对象。
disconnectPacketBuilder.BeginDisconnect();
}
else
{
// 可以选择在这里添加一个日志消息,表示客户端对象已经为 null,无需断开连接。
Debug.Log("Client is already null, no need to disconnect.");
}
}
/// <summary>
/// 构建连接对象
/// </summary>
/// <param name="client"></param>
/// <param name="builder"></param>
/// <returns></returns>
private ConnectPacketBuilder ConnectPacketBuilderCallback(MQTTClient client, ConnectPacketBuilder builder)
{
//设置账号密码clientId,Session
return builder.WithUserName(userName).WithPassword(psd).WithClientID(clientId).WithCleanStart();
// return builder.WithUserName(userName).WithPassword(psd).WithClientID(clientId);
}
//记录Mqtt客户端连接状态的改变
private void OnStateChanged(MQTTClient client, ClientStates oldState, ClientStates newState)
{
Debug.Log($"状态改变:{oldState} => {newState}");
}
//在断开连接的时候调用
private void OnDisconnected(MQTTClient client, DisconnectReasonCodes code, string reason)
{
Debug.Log($"连接断开: OnDisconnected - code: {code}, reason: '{reason}'");
}
//在出错的时候调用
private void OnError(MQTTClient client, string reason)
{
Debug.Log($"发生错误:OnError reason: '{reason}'");
}
}