1.环境准备
HslCommunication.dll (版本:11.5.3.0)
Newtonsoft.Json.dll (版本 13.0.1.25517)
dll自取
2.client相关
using UnityEngine;
using HslCommunication.MQTT;
using System.Text;
using System;
using UnityEngine.Networking;
using System.Collections;
using Google.Protobuf;
using Newtonsoft.Json;
public class MqttManager : MonoBehaviour
{
private MqttClient mqttClient;
void Start()
{
StartCoroutine(Post(OnWebCallback));
}
//post 请求 获取mqtt信息 业务相关代码和谐掉了
public IEnumerator Post(Action<string> callback)
{
// yield return new WaitForSeconds(5f);
string url = "www.baidu.com";
var request = new UnityWebRequest(url, "POST");
string json = "~~~";
byte[] bodyRaw = new System.Text.UTF8Encoding(true).GetBytes(json);
request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
yield return request.SendWebRequest();
if (request.result == UnityWebRequest.Result.ConnectionError || request.result == UnityWebRequest.Result.ProtocolError)
{
Debug.Log(request.error);
}
else
{
callback(request.downloadHandler.text);
}
}
private void OnWebCallback(string obj)
{
WebLoginData entity = JsonConvert.DeserializeObject<WebLoginData>(obj);
mqttClient = new MqttClient(new MqttConnectionOptions()
{
ClientId = entity.result.mqttClientId, // 客户端的唯一的ID信息
IpAddress = entity.result.mqttHost, //"127.0.0.1", // 服务器的地址
// Port = 8083, // 端口
UseSSL = false,
Credentials = new MqttCredential() { UserName = entity.result.mqttUserName, Password = entity.result.mqttPassword },
CleanSession = true,
});
// 连接服务器
HslCommunication.OperateResult connect = mqttClient.ConnectServer();
if (connect.IsSuccess)
{
// 连接成功
UnityEngine.Debug.Log("连接成功");
}
else
{
// 连接失败,过会就需要重新连接了
UnityEngine.Debug.Log("连接失败");
}
// 然后添加订阅
// HslCommunication.OperateResult sub = mqttClient.SubscribeMessage("test");
if (sub.IsSuccess)
{
// 订阅成功
UnityEngine.Debug.Log("订阅成功");
}
else
{
// 订阅失败
UnityEngine.Debug.Log("订阅失败");
}
// 订阅示例
mqttClient.OnMqttMessageReceived += (MqttClient client, string topic, byte[] payload) =>
{
//业务
};
}
}
3.server相关
server 我使用的是 mosquitto
mqtt server 自取
mosquitto:代理器主程序
mosquitto.conf:配置文件
mosquitto_passwd:用户密码管理工具
mosquitto_pub:用于发布消息的命令行客户端
mosquitto_sub:用于订阅消息的命令行客户端
mqtt:MQTT的后台进程
libmosquitto:客户端编译的库文件
参数说明
-c 启动mosquitto可以调整的参数,配置文件
-d 表示MQTT mosquitto将在后台运行。
-p 代表当前的mosquitto服务实例启动以后,其监听端口号
-v 代码调试模式(verbose)
启动服务器 (我在这里使用cmd 调用会报错 后来使用 powershell.exe 调用命令并未报错)
mosquitto -c /etc/mosquitto/mosquitto.conf -d
服务器配置文章来源:https://www.toymoban.com/news/detail-756487.html
mosquitto.conf配置文件,1、监听的端口;2、不允许匿名登陆;3、登陆账号信息的文件文章来源地址https://www.toymoban.com/news/detail-756487.html
listener 1883
allow_anonymous false
password_file /etc/mosquitto/passwd
到了这里,关于unity接入mqtt自救指南的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!