vanturman 2020-04-10
适用范围:
在低带宽、不可靠的网络下提供基于云平台的远程设备的数据传输和监控。
原理图:
MQTT开发文档:
http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html
Unity3D开发引入MQTT时候进行封装成M2MQTT,通过GiitHub下载M2MQTT,很多,导入你的Unity工程,这里就不介绍了。
第一步:因为MQTT中间需要消息代理,所以我们首先得搭建代理服务器,我这里使用得是apache-apollo-1.7.1服务,安装过程百度,注册登录
需要选择协议。
第二步:就是要在Unity进行开发了,直接上代码吧
using System.Net; using uPLibrary.Networking.M2Mqtt; using uPLibrary.Networking.M2Mqtt.Messages; /// <summary> /// 连接 /// </summary> public void onConnect() { string txtIP = ip.text; string txtPort = port.text; string clientId = Guid.NewGuid().ToString(); //服务器默认密码是这个 string username = "admin"; string password = "password"; client = new MqttClient(IPAddress.Parse(txtIP), int.Parse(txtPort), false, null); client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived; client.MqttMsgSubscribed += Client_MqttMsgSubscribed; client.Connect(clientId, username, password); } /// <summary> /// 断开连接 /// </summary> client.Disconnect(); //订阅主题 if (client != null&&subscribe_chanel.text!="") { client.Subscribe(new string[] { subscribe_chanel.text }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE }); } //订阅回调 private void Client_MqttMsgSubscribed(object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgSubscribedEventArgs e) { Debug.Log("订阅" + e.MessageId); } //发布消息 if (client != null && publish_chanel.text != "") { client.Publish(publish_chanel.text, System.Text.Encoding.UTF8.GetBytes(publish_content.text), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false); } //接受消息 private void Client_MqttMsgPublishReceived(object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPublishEventArgs e) { string message=System.Text.Encoding.UTF8.GetString(e.Message); receive_message = message; Debug.Log("接收到消息是"+message); }
主要的方法都在上面了,而且我测试过了,信息谁可以接受到的,如果大家还想设置更多条件,可以在我上面发的开发文档链接中继续探索。