栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 游戏开发 > 其他

Unity MQTT 客户端 (M2MQTT) 已封模块直接用

其他 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Unity MQTT 客户端 (M2MQTT) 已封模块直接用

前言

不好意思,我又来趟坑了,最近玩MQTT玩的甚欢…
查了一圈帖子Unity用M2MQTT开发的话比较心情愉悦,

具体搭建过程请参考这篇帖子:
MQTT学习(四)–使用m2mqtt在Unity3D中实现MQTT客户端

上干货! 下载vovacooper/Unity3d_MQTT库:

github:https://github.com/vovacooper/Unity3d_MQTT
codechina:https://codechina.csdn.net/mirrors/vovacooper/Unity3d_MQTT
fastgit:https://hub.fastgit.org/vovacooper/Unity3d_MQTT
(Github上不去的用后面这两个下载)

导入包

打开下载的压缩包文件,
找到Unity3d_MQTT-master.zip/Unity3d_MQTT-master/Packages/unity3d_mqtt.unitypackage这个文件解压出来,丢到unity里面.

再上干货

为了便于调用,我将这个库又封装了一层.效果是酱式儿的:

这样一来用起来就很舒服了…

上家伙

复制保存MqttEvents.cs,随便挂一个物体上即可使用!

using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using System.Collections;
using System.Net;
using System.Text;
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;


public class MqttEvents : MonoBehaviour
{


    public MqttClient client;
    [Header("服务器设定")]
    public bool debug = false;
    public string ip = "127.0.0.1";
    public int port = 1883;
    public string username = "smcc";
    public string password = "123123";
    public bool autoConnect = true;
    public bool autoReconnect = true;
    [Header("自动订阅主题")]
    public int qos = 0;
    public string[] toppics;
    [Header("MQTT事件绑定")]
    public MqttEvent_OnBegin onBeginCall;
    public MqttEvent_OnConnect onConnectCall;
    public MqttEvent_OnReonnect onReconnectCall;
    public MqttEvent_OnDisconnect onDisconnectCall;
    public MqttEvent_OnMsg onMsgCall;
    private List _MqttMsgDatas = new List();


    // Use this for initialization
    void Start()
    {

        // create client instance 
        client = new MqttClient(IPAddress.Parse(ip), port, false, null);

        // register to message received 
        client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
        client.MqttMsgDisconnected += client_MqttMsgDisconnected;
        
        onBeginCall.Invoke(this);
        if (autoConnect) connect();

    }
    public void connect()
    {

        string clientId = "CONTROL_CLIENT_" + Guid.NewGuid().ToString();
        if (debug) client.Connect(clientId, username, password);
        if (client.IsConnected)
        {
            if (debug) Debug.Log("[MQTT]连接服务器成功!" + client.IsConnected);
            onConnectCall.Invoke(client);
            //开始订阅主题
            if (toppics.Length > 0)
            {
                byte[] qoss = new byte[toppics.Length];
                for (int i = 0; i < qoss.Length; i++) qoss[i] = (byte)qos;
                client.Subscribe(toppics, qoss);
            }

        }
        else
        {
            if (debug) Debug.LogWarning("[MQTT]连接服务器失败!" + client.IsConnected);
            onDisconnectCall.Invoke(client);
            if (autoReconnect) StartCoroutine(reConnect());
        }
        float ts = Time.time;
    }


    void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
    {
        string msg = Encoding.UTF8.GetString(e.Message);
        if (debug) Debug.Log("[MQTT]消息抵达: " + e.Topic + " " + msg);
        //这个事件是多线程调用的,我们需要把它转到Update里面让主线程去运行,不然在进行调用资源的时候unity会报错.
        MqttMsgData args = new MqttMsgData();
        args.Message = msg;
        args.Topic = e.Topic;
        _MqttMsgDatas.Add(args);



    }
    void client_MqttMsgDisconnected(object sender, System.EventArgs e)
    {
        if (debug) Debug.Log("[MQTT]服务器连接中断..." + e);
        onDisconnectCall.Invoke(client);
        if (autoReconnect) StartCoroutine(reConnect());
    }
    IEnumerator reConnect()
    {
        yield return new WaitForSeconds(1);
        if (debug) Debug.Log("[MQTT]正在重新连接服务器...");
        onReconnectCall.Invoke(client);
        connect();
    }
    
    public void send(string topic, string str)
    {
        client.Publish(topic, System.Text.Encoding.UTF8.GetBytes(str), (byte)qos, false);
    }

    //监听断开事件不激活,不知道怎么地了
    //这里用Update监控模拟断开事件
    private bool lastConnected = false;
    void Update()
    {

        //Debug.Log(client.IsConnected);
        if (client.IsConnected != lastConnected)
        {
            lastConnected = client.IsConnected;
            if (!lastConnected)
            {
                onDisconnectCall.Invoke(client);
            }

        }

        //将其他线程转换到主线程激活,不然unity会报错
        while (_MqttMsgDatas.Count > 0)
        {
            MqttMsgData args = _MqttMsgDatas[0];
            _MqttMsgDatas.RemoveAt(0);
            onMsgCall.Invoke(this, args.Topic, args.Message);
        }
    }

}

[Serializable]
public class MqttEvent_OnBegin : UnityEvent { }


[Serializable]
public class MqttEvent_OnMsg : UnityEvent { }

[Serializable]
public class MqttEvent_OnDisconnect : UnityEvent { }

[Serializable]
public class MqttEvent_OnConnect : UnityEvent { }
[Serializable]
public class MqttEvent_OnReonnect : UnityEvent { }

struct MqttMsgData
{
    public string Topic { get; set; }
    public string Message { get; set; }
}

这东西用起来也很简单,你只需要创建一个脚本,根据事件类型创建对应接收函数即可!
666,别忘点个

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/905948.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号