具体关于MQTT是什么具体就不说了,百度一下,你就知道。这里用的是M2Mqtt的类库。可以去查官网然后Git下来自己生成一下。接下来直接上unity客户端的本地代码:
需要提前导入生成的DLL。
- using UnityEngine;
- using System.Collections;
- using System.Net;
- using System.Text;
- using uPLibrary.Networking.M2Mqtt;
- using uPLibrary.Networking.M2Mqtt.Messages;
-
- public class Mqtt : MonoBehaviour
- {
-
- private MqttClient mqttClient;
-
- void Awake()
- {
-
- mqttClient = new MqttClient(IPAddress.Parse("192.168.1.163"));
-
-
- mqttClient.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
-
- mqttClient.Connect("zsc");
-
- mqttClient.Subscribe(new string[] { "fps" }, new byte[] { MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE });
- }
- void Start () {
-
- }
-
-
- void Update () {
-
- if (Input.GetMouseButtonDown(0))
- {
-
- string strValue = "123";
-
- mqttClient.Publish("klabs", Encoding.UTF8.GetBytes(strValue));
- Debug.Log("发送数据123");
- }
- }
-
- static void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
- {
-
- Debug.Log("返回数据");
- string msg = System.Text.Encoding.Default.GetString(e.Message);
- Debug.Log(msg);
- }
- }