close

嗯...許久沒更新這個部落格了

這篇記錄了在Unity上使用M2MQTT這個Library

至於MQTT是什麼?網路上有很多說明了,我就不贅述了

 

MQTT Broker設置(以Windows 64bit為例)

請參考這篇的做法,其中安裝時的Service選項建議打開,否則一旦在Terminal中開啟後要關掉會很麻煩

如果把它設置成Service的話,要關掉隨時都能去service.msc那邊關閉它

 

Unity端的MQTT

1.先到NuGet下載M2MQTT(https://www.nuget.org/packages/M2Mqtt/)

image

 

2.將下載的檔案副檔名由unpkg改為zip

image

 

3.打開Unity Hub,建立一個專案(2D或3D都沒差),然後在Assets資料夾下新增一個Plugins,並把上面壓縮檔內(lib\net45)的兩個檔案都解壓縮到這個Plugins內

image

 

4.在Assets下新增兩個腳本,分別叫做Publisher.cs和Subscriber.cs

image

 

5.開始撰寫Subscriber.cs程式碼

using System.Text;
using UnityEngine;
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;

public class Subscriber : MonoBehaviour
{
    private MqttClient client;

    private void Start()
    {
        client = new MqttClient("127.0.0.1");//MQTT Broker的IP
        client.MqttMsgPublishReceived += Receive;//接收到資料時要執行的方法

        /*
         * 開始連線,第一個傳入的參數是Client ID,目的是用來在Broker內判斷你是誰
         * 如果MQTT Broker需要帳號密碼才能連線,則可在Connect方法內額外傳入
         */
        client.Connect("Subscriber");

        /* 
         * 訂閱主題
         * 可以一次訂閱多個主題
         * 每個主題都有一個QoS品質參數
         * MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE:最多傳送一次
         * MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE:至少傳送一次
         * MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE:確實傳送一次
         */
        client.Subscribe(new string[] { "Record" }, new byte[] { MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE });
    }

    private void Receive(object sender, MqttMsgPublishEventArgs e)
    {
        Debug.Log("Topic:" + e.Topic + ", Message:" + Encoding.UTF8.GetString(e.Message));
    }

    private void OnDisable()
    {
        client.Unsubscribe(new string[] { "Record" });//當程式關閉時,取消訂閱
    }
}


 

6.開始撰寫Publisher.cs

using System.Text;
using UnityEngine;
using uPLibrary.Networking.M2Mqtt;

public class Publisher : MonoBehaviour
{
    private MqttClient client;
    public int count = 0;

    private void Start()
    {
        client = new MqttClient("127.0.0.1");//MQTT Broker的IP

        /*
         * 開始連線,第一個傳入的參數是Client ID,目的是用來在Broker內判斷你是誰
         * 如果MQTT Broker需要帳號密碼才能連線,則可在Connect方法內額外傳入
         */
        client.Connect("Publisher");
    }

    private void OnGUI()
    {
        if(GUILayout.Button("Publish message"))
        {
            client.Publish("Record", Encoding.UTF8.GetBytes("Hello, This is the " + count + " message."));
            count++;
        }
    }
}


 

7.把 Subscriber.cs 和 Publisher.cs 都掛到MainCamera上

image

 

8.接著根據最前面MQTT Broker的安裝教學,先開啟MQTT Broker

image

 

9.執行Unity端的程式,可以看到MQTT Broker顯示了連線資訊

image

 

10.點擊Game視窗左上的Publish message按鈕,Subscriber會接收到訊息並把訊息印出來

image

image

MQTT Broker也會顯示有訊息被發送到Record這個Topic

image

arrow
arrow
    文章標籤
    程式語言
    全站熱搜

    Yang 發表在 痞客邦 留言(0) 人氣()