前言
不好意思,我又来趟坑了,最近玩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<MqttMsgData> _MqttMsgDatas = new List<MqttMsgData>();
void Start()
{
client = new MqttClient(IPAddress.Parse(ip), port, false, null);
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);
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);
}
private bool lastConnected = false;
void Update()
{
if (client.IsConnected != lastConnected)
{
lastConnected = client.IsConnected;
if (!lastConnected)
{
onDisconnectCall.Invoke(client);
}
}
while (_MqttMsgDatas.Count > 0)
{
MqttMsgData args = _MqttMsgDatas[0];
_MqttMsgDatas.RemoveAt(0);
onMsgCall.Invoke(this, args.Topic, args.Message);
}
}
}
[Serializable]
public class MqttEvent_OnBegin : UnityEvent<MqttEvents> { }
[Serializable]
public class MqttEvent_OnMsg : UnityEvent<MqttEvents, string, string> { }
[Serializable]
public class MqttEvent_OnDisconnect : UnityEvent<MqttClient> { }
[Serializable]
public class MqttEvent_OnConnect : UnityEvent<MqttClient> { }
[Serializable]
public class MqttEvent_OnReonnect : UnityEvent<MqttClient> { }
struct MqttMsgData
{
public string Topic { get; set; }
public string Message { get; set; }
}
这东西用起来也很简单,你只需要创建一个脚本,根据事件类型创建对应接收函数即可! 666,别忘点个
|