在unity3d中接受MQTT消息协议数据C# .net,M2Mqtt

来源:互联网 发布:sql优化 面试题 编辑:程序博客网 时间:2024/06/03 03:27

具体关于MQTT是什么具体就不说了,百度一下,你就知道。这里用的是M2Mqtt的类库。可以去查官网然后Git下来自己生成一下。接下来直接上unity客户端的本地代码:

需要提前导入生成的DLL。

[csharp] view plain copy
  1. using UnityEngine;  
  2. using System.Collections;  
  3. using System.Net;  
  4. using System.Text;  
  5. using uPLibrary.Networking.M2Mqtt;  
  6. using uPLibrary.Networking.M2Mqtt.Messages;  
  7.   
  8. public class Mqtt : MonoBehaviour  
  9. {  
  10.   
  11.     private MqttClient mqttClient;  
  12.   
  13.     void Awake()  
  14.     {  
  15.         //链接服务器  
  16.         mqttClient = new MqttClient(IPAddress.Parse("192.168.1.163"));  
  17.          
  18.         //注册服务器返回信息接受函数  
  19.         mqttClient.MqttMsgPublishReceived += client_MqttMsgPublishReceived;  
  20.         //客户端ID  一个字符串  
  21.         mqttClient.Connect("zsc");  
  22.         //监听FPS字段的返回数据  
  23.         mqttClient.Subscribe(new string[] { "fps" }, new byte[] { MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE });  
  24.     }  
  25.     void Start () {  
  26.       
  27.     }  
  28.       
  29.     // Update is called once per frame  
  30.     void Update () {  
  31.   
  32.         if (Input.GetMouseButtonDown(0))  
  33.         {  
  34.             //这个字符串是向服务器发送的数据信息  
  35.             string strValue = "123";  
  36.             // 发送一个内容是123 字段是klabs的信息  
  37.             mqttClient.Publish("klabs", Encoding.UTF8.GetBytes(strValue));   
  38.             Debug.Log("发送数据123");  
  39.         }  
  40.     }  
  41.   
  42.     static void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)  
  43.     {  
  44.         // handle message received  
  45.         Debug.Log("返回数据");  
  46.         string msg = System.Text.Encoding.Default.GetString(e.Message);  
  47.         Debug.Log(msg);  
  48.     }  
  49. }  

原创粉丝点击