【发布时间】:2017-04-12 10:18:21
【问题描述】:
伙计们!我一直在使用 Unity,以便使用 MQTT 协议将 Microsoft Hololens 的 Unity 应用程序连接到服务器。我在 Github 上找到了一个名为 Unity3d MQTT 的项目,这似乎符合我的目的。
然后,我在 Unity 中制作了一个名为 MQTTLListener 的 C# 脚本。写法如下:
using System.Security.Cryptography.X509Certificates;
using UnityEngine;
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;
public class MQTTListener : MonoBehaviour{
private const int port = 8883;
private readonly string deviceId = "<deviceId>";
private readonly string hubAddress = "<hubAddress>";
private readonly string password = "<sasToken>";
private MqttClient client;
private string username;
public TextAsset certificate;
void Start(){
// Forming a certificate based on a TextAsset
var cert = new X509Certificate();
cert.Import(this.certificate.bytes);
// Making a new MQTT client with the formed certificate
this.client = new MqttClient(
brokerHostName: this.hubAddress,
brokerPort: MQTTListener.port,
secure: true,
caCert: cert
);
// Initializing MQTT listener events
this.client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;
this.username = "/" + deviceId;
// Establish a connection to the target device
this.client.Connect(
clientId: this.deviceId,
username: this.username,
password: this.password
);
var hubTopicSubscribe = "/devices/" + this.deviceId + "/messages/devicebound/#";
this.client.Subscribe(
new string[]{ hubTopicSubscribe },
new byte[]{ MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE } // QoS = Quality of Service
);
}
private void Client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e){
Debug.Log("Received: " + System.Text.Encoding.UTF8.GetString(e.Message));
}
void Update(){
}
}
代码编译正常,但后来我遇到了以下问题:
ArgumentException:库编译时不支持 SSL
uPLibrary.Networking.M2Mqtt.MqttClient.Init (System.String brokerHostName,System.Net.IPAddress brokerIpAddress,Int32 brokerPort,布尔安全, System.Security.Cryptography.X509Certificates.X509Certificate caCert)
(在 Assets/MQTT/scripts/MqttClient.cs:320) uPLibrary.Networking.M2Mqtt.MqttClient..ctor (System.String brokerHostName,Int32 brokerPort,布尔安全, System.Security.Cryptography.X509Certificates.X509Certificate caCert) (在 Assets/MQTT/scripts/MqttClient.cs:268) MQTTLListener.Start() (在 Assets/HoloProject/Scripts/MQTTLListener.cs:26)
看起来很简单,但实际上我如何编译支持 SSL 的库(无论它在哪里)?
【问题讨论】:
-
快速浏览似乎表明您只需要在构建时定义
SSL。 -
@Bart 如何在 C# 中定义它?
-
鉴于您在 Unity 中工作,对于每个检查
SSL指令的文件,您都可以在顶部添加一个#define SSL。或者你去你的播放器设置,在“其他设置”中你会找到一个“脚本定义符号”文本框,你可以在其中添加SSL。
标签: c# ssl unity3d mqtt tls1.2