上一篇講解了MQTT協議在JS實現,通過和Unity3D交互實現通信,因爲對JS不是特別精通,所以講得比較粗略。這一篇中,介紹Unity3D 實現MQTT協議通信,將細緻講解過程
MQTT是IBM開源的一個通訊方式,是一個基於TCP的發佈訂閱協議,MQTT使用類似MQ常用的發佈/訂閱模式,起到應用程序解耦,異步消息,削峯填谷的作用。
優點:
- 使用發佈/訂閱模式,提供一對多的消息發佈,使消息發送者和接收者在時間和空間上解耦。
- 二進制協議, 網絡傳輸開銷非常小(固定頭部是2字節)。
- 靈活的Topic訂閱、 Qos、臨終遺言等特性。
缺點: - 集中化部署,服務端壓力大,需要考慮流程控制及高可用。
- 對於請求/響應模式的支持需要在應用層根據消息ID做發佈主題和訂閱主題。
適用範圍:
在低帶寬、不可靠的網絡下提供基於雲平臺的遠程設備的數據傳輸和監控。
原理圖:
MQTT開發文檔:
http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html
Unity3D開發引入MQTT時候進行封裝成M2MQTT,通過GiitHub下載M2MQTT,很多,導入你的Unity工程,這裏就不介紹了。
第一步:因爲MQTT中間需要消息代理,所以我們首先得搭建代理服務器,我這裏使用得是apache-apollo-1.7.1服務,安裝過程百度,註冊登錄
需要選擇協議。
第二步:就是要在Unity進行開發了,直接上代碼吧
using System.Net;
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;
/// <summary>
/// 連接
/// </summary>
public void onConnect()
{
string txtIP = ip.text;
string txtPort = port.text;
string clientId = Guid.NewGuid().ToString();
//服務器默認密碼是這個
string username = "admin";
string password = "password";
client = new MqttClient(IPAddress.Parse(txtIP), int.Parse(txtPort), false, null);
client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;
client.MqttMsgSubscribed += Client_MqttMsgSubscribed;
client.Connect(clientId, username, password);
}
/// <summary>
/// 斷開連接
/// </summary>
client.Disconnect();
//訂閱主題
if (client != null&&subscribe_chanel.text!="")
{
client.Subscribe(new string[] { subscribe_chanel.text }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
}
//訂閱回調
private void Client_MqttMsgSubscribed(object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgSubscribedEventArgs e)
{
Debug.Log("訂閱" + e.MessageId);
}
//發佈消息
if (client != null && publish_chanel.text != "")
{
client.Publish(publish_chanel.text, System.Text.Encoding.UTF8.GetBytes(publish_content.text), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false);
}
//接受消息
private void Client_MqttMsgPublishReceived(object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPublishEventArgs e)
{
string message=System.Text.Encoding.UTF8.GetString(e.Message);
receive_message = message;
Debug.Log("接收到消息是"+message);
}
主要的方法都在上面了,而且我測試過了,信息誰可以接受到的,如果大家還想設置更多條件,可以在我上面發的開發文檔鏈接中繼續探索。