Application of MQTT Communication Protocol in Unity II-Implementation of Unity3D C#

Keywords: ASP.NET Unity encoding network Apache

The previous article explained the implementation of MQTT protocol in JS by interacting with Unity3D, which is rather rough because it is not particularly proficient with JS.In this article, Unity3D is introduced to implement MQTT protocol communication, and the process is explained in detail.
MQTT is an open source communication method of IBM and a TCP-based publishing and subscription protocol. MQTT uses a publishing/subscription mode similar to that commonly used by MQ to decouple applications, asynchronous messages, and cut corners and valleys.
Advantage:

  • Publish/Subscribe mode provides one-to-many message publishing, decoupling the sender and receiver of messages in time and space.
  • Binary protocol, network transmission overhead is very small (fixed header is 2 bytes).
  • Flexible Topic Subscription, Qos, Ending Message, etc.
    Disadvantages:
  • Centralized deployment, high service pressure, process control and high availability need to be considered.
  • Support for request/response mode requires publishing and subscription topics at the application level based on the message ID.

Scope of application:
Provides data transfer and monitoring for remote devices based on cloud platforms over low-bandwidth, unreliable networks.

Schematic diagram:

MQTT development documentation:
http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html

When Unity3D development introduced MQTT, it was encapsulated as M2MQTT, downloaded through GiitHub, many of which were imported into your Unity project, which is not described here.

Step 1: Because there is a need for message proxy in MQTT, we have to set up a proxy server first. I use apache-apollo-1.7.1 service here. Baidu is installed and registered for login

A protocol needs to be selected.
Step 2: To develop in Unity, go directly to the code

using System.Net;
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;

 /// <summary>
    ///Connect
    /// </summary>
    public void  onConnect()
    {
        string txtIP = ip.text;
        string txtPort = port.text;
        string clientId = Guid.NewGuid().ToString();
        //The server default password is this
        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>
      ///Disconnect
      /// </summary>
      client.Disconnect();

        //Subscription Subject
          if (client != null&&subscribe_chanel.text!="")
            {
                client.Subscribe(new string[] { subscribe_chanel.text }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
            }

                        //Subscription Callbacks
                         private void Client_MqttMsgSubscribed(object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgSubscribedEventArgs e)
    {
        Debug.Log("Subscribe" + e.MessageId);
    }

                        //Publish a message
                         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);
            }

                        //Accept message
                           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("Received message is"+message);
    }

The main methods are all above, and I've tested who can receive the information. If you want to set more conditions, you can continue to explore in the link to the development document that I posted above.

Posted by CSB on Thu, 09 Apr 2020 15:26:03 -0700