Unity的MQTT简单的Demo以及简单的代码介绍
Github下载地址
https://github.com/laurentva/Pozyx-Unity-MQTT
打不开评论我给你发过去
连接代码
- 下载之后使用UnityHub打开项目
- 打开
Mqtt_Test
using UnityEngine;
using System.Net;
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;
using System;
public class mqttTest : MonoBehaviour {
private MqttClient client;
// Use this for initialization
void Start () {
// create client instance
client = new MqttClient(IPAddress.Parse("143.185.118.233"),8080 , false , null ); //创建一个MQTT客户端连接
// register to message received
client.MqttMsgPublishReceived += client_MqttMsgPublishReceived; //接收数据
string clientId = Guid.NewGuid().ToString(); //随机一个ClientID
client.Connect(clientId); //连接到MQTT服务器
// subscribe to the topic "/home/temperature" with QoS 2
client.Subscribe(new string[] { "hello/world" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE }); //订阅主题并设置订阅的方式
//主题是hello/world
}
///接收到消息推送
void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
{
Debug.Log("Received: " + System.Text.Encoding.UTF8.GetString(e.Message) );
}
void OnGUI(){
if ( GUI.Button (new Rect (20,40,80,20), "Level 1")) {
Debug.Log("sending...");
client.Publish("hello/world", System.Text.Encoding.UTF8.GetBytes("Sending from Unity3D!!!"), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, true);//发送消息
Debug.Log("sent");
}
}
}
代码修改
代码修改了IP,这样就可以使用公开的MQTT服务进行测试了
using UnityEngine;
using System.Net;
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;
using System;
public class mqttTest : MonoBehaviour {
private MqttClient client;
// Use this for initialization
void Start () {
IPHostEntry host = Dns.GetHostByName("test.ranye-iot.net");//根据域名获取ip,这里使用的是一个免费的MQTT服务器
IPAddress ip = host.AddressList[0];
string ipStr= ip.ToString();
client = new MqttClient(IPAddress.Parse(ipStr), 1883, false, null);//连接
// register to message received
client.MqttMsgPublishReceived += client_MqttMsgPublishReceived; //接收数据
string clientId = Guid.NewGuid().ToString(); //随机一个ClientID
client.Connect(clientId); //连接到MQTT服务器
// subscribe to the topic "/home/temperature" with QoS 2
client.Subscribe(new string[] { "hello/world" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE }); //订阅主题并设置订阅的方式
//主题是hello/world
}
///接收到消息推送
void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
{
Debug.Log("Received: " + System.Text.Encoding.UTF8.GetString(e.Message) );
}
void OnGUI(){
if ( GUI.Button (new Rect (20,40,80,20), "Level 1")) {
Debug.Log("sending...");
client.Publish("hello/world", System.Text.Encoding.UTF8.GetBytes("Sending from Unity3D!!!"), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, true);//发送消息
}
}
}
具体的东西在Github的下载地址里面有作者写的更加详细的说明。
不懂评论Enjoy
。