The second application of MQTT communication protocol in Unity-Unity3D C # implementation

The previous article explained that the MQTT protocol is implemented in JS, and communicates with Unity3D. Because it is not particularly proficient in JS, it is relatively sketchy. In this article, we introduce Unity3D to implement MQTT protocol communication. We will explain the process in detail.
MQTT is an open source communication method of IBM. It is a TCP-based publish and subscribe protocol. MQTT uses a similar publish / subscribe model that MQ commonly uses to play application solutions. Coupling, asynchronous messages, peak clipping and valley filling.
advantage:

  • Use the publish / subscribe model to provide one-to-many message publishing, so that the sender and receiver of the message are decoupled in time and space.
  • Binary protocol, network transmission overhead is very small (fixed header is 2 bytes).
  • Flexible Topic subscription, Qos, hospice and other features.
    Disadvantages:
  • Centralized deployment, high pressure on the server side, process control and high availability need to be considered.
  • Support for the request / response model requires publishing topics and subscribing topics based on the message ID at the application layer.

Scope of application:
Provide data transmission and monitoring of remote devices based on cloud platforms under low bandwidth and unreliable networks.

Schematic diagram:
The second application of MQTT communication protocol in Unity-Unity3D C # implementation

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

Unity3D development packaged into M2MQTT when introducing MQTT, download M2MQTT through GiitHub, many, import your Unity project, not introduced here.

The first step: because MQTT needs a message broker in the middle, we must first build a proxy server. I use the apache-apollo-1.7.1 service here. Baidu is installed during the installation process. Registering and logging in
The second application of MQTT communication protocol in Unity-Unity3D C # implementation
requires a protocol.
The second step: is to develop in Unity, directly on the code

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);
    }

The main methods are all above, and I have tested it, who can receive the information, if you want to set more conditions, you can continue to explore in the link of the development document I sent above.

Guess you like

Origin blog.51cto.com/myselfdream/2486101