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

具体关于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. }  

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值