Unity 3D uses MQTT to realize data communication

Recently, I need to use MQTT communication in Unity for learning. CSDN downloaded some materials and reported errors (mainly because I don’t understand the code and will not change it). I reproduced a simple demo with station B up, which deepened some learning. , beginners in need can pick it up by themselves.

The demo implementation steps are roughly as follows

1. Add HslCommunication component

 To download a HslCommunication first , select these two files in the folder and drag them directly to unity

 2. Unity creates a script file, compiles it and throws it directly on the camera, and it’s over. Upload the code, and change the topic according to the requirements

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using HslCommunication.MQTT;
using System.Text;
using System.Diagnostics;
using System;

public class mqtt_test : MonoBehaviour
{
    private MqttClient mqttClient;
    // Start is called before the first frame update
    void Start()
    {
        mqttClient = new MqttClient(new MqttConnectionOptions()
        {
            ClientId = "ABC",                     // 客户端的唯一的ID信息
            IpAddress = "127.0.0.1",              // 服务器的地址
        });
        // 连接服务器
        HslCommunication.OperateResult connect = mqttClient.ConnectServer();
        if (connect.IsSuccess)
        {
            // 连接成功
            UnityEngine.Debug.Log("连接成功");
        }
        else
        {
            // 连接失败,过会就需要重新连接了
            UnityEngine.Debug.Log("连接失败");
        }
        // 然后添加订阅
        HslCommunication.OperateResult sub = mqttClient.SubscribeMessage("test");
        if (sub.IsSuccess)
        {
            // 订阅成功
            UnityEngine.Debug.Log("订阅成功");
        }
        else
        {
            // 订阅失败
            UnityEngine.Debug.Log("订阅失败");
        }
        // 订阅示例
        mqttClient.OnMqttMessageReceived += (MqttClient client, string topic, byte[] payload) =>
        {
            //Console.WriteLine("Time:" + DateTime.Now.ToString());
            //Console.WriteLine("Topic:" + topic);
            //Console.WriteLine("Payload:" + Encoding.UTF8.GetString(payload));
            UnityEngine.Debug.Log("Time:" + DateTime.Now.ToString());
            UnityEngine.Debug.Log("Topic:" + topic);
            UnityEngine.Debug.Log("Payload:" + Encoding.UTF8.GetString(payload));
        };


    }

    // Update is called once per frame
    void Update()
    {
        if(Input.GetKey(KeyCode.Space))
        {
            HslCommunication.OperateResult connect = mqttClient.PublishMessage(new MqttApplicationMessage()
            {
                Topic = "/AAA",                 //主题
                QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce,       //如果是实时数据,适合用这个
                Payload = Encoding.UTF8.GetBytes("Test data")
            });
            if(connect.IsSuccess)
            {
                //发布成功
                UnityEngine.Debug.Log("发布成功");
            }
            else
            {
                UnityEngine.Debug.Log("发布失败");
            }
        }
    }
}

 3. (1) Run the scene in Unity

    (2) Joint debugging with MQTTX (MQTTfx is also available), the address is the same, and the theme is corresponding.

Subscribe to the topic of MQTTX

Press the space to publish the message "Test data", MQTTX subscribes to the topic on the Unity side, and the published message is received successfully

 

 

 

Guess you like

Origin blog.csdn.net/weixin_57716672/article/details/127301984