mqant在Unity3d前端使用
发布于 1 年前 作者 Symanyang 1174 次浏览 来自 分享

mqant支持的mqtt协议版本是3.1的,而Unity3D支持的class库是.netframework3.5及以下的,所以在选择m2mqtt版本的时候要注意runtime版本(.netframework版本)。 在用之前,有必要弄清楚mqtt、m2mqtt以及.netframework的相互关系是:mqtt是协议,m2mqtt是基于mqtt的实现,而.netframework与m2mqtt的实现有关,因为在写class库时,有选择支持的框架的 image.png 所以在unity3d选择使用m2mqtt的时候既要注意使用mqtt的版本,也要注意.nerframework版本!

mqant对于客户端使用还是很友好的,只要连接上之后,除了发布信息,是不用向客户端订阅信息就能收到服务器发来的主题信息,再根据主题名字来处理信息 连接服务器的代码如下:

		//连接第一个参数是ip地址,第二个参数是端口地址
		client = new MqttClient(IPAddress.Parse(SysDefine.Network_ip), SysDefine.Network_post, false, null);
        client.Connect(SysDefine.Network_userName);   
        if (!client.IsConnected)
        {
            Debug.Log("havent connect to server");
            return;
        }
        //注册消息接受事件
        client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
		//发布信息
		client.Publish(“{Topic/topicename}“, Encoding.UTF8.GetBytes("{\"sdshdg\": \"dswdd\"}"), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false);
		
    //订阅反馈
    void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
    {
        
        if (e.Topic == SysDefine.Topics.CountDown_Topics)
        {
				//对接受的数据进行解析
				string msg = System.Text.Encoding.Default.GetString(e.Message);		
				JsonData data = JsonMapper.ToObject(msg);
        }
        else if (e.Topic == "FightSys/symann")
        {
		
        }
    }
4 回复

如果有完整代码就更好了

@liangdas 老大,我下载的是 ,https://github.com/eclipse/paho.mqtt.m2mqtt 直接copy 到unity3d。直接代码 copy untiy3d ,处理一点引用问题,运行链接 mqant-chat。。是什么问题? MqttCommunicationException: Exception of type ‘uPLibrary.Networking.M2Mqtt.Exceptions.MqttCommunicationException’ was thrown. uPLibrary.Networking.M2Mqtt.MqttClient.SendReceive (System.Byte[] msgBytes, Int32 timeout) (at Assets/MQTT/scripts/MqttClient.cs:1090) uPLibrary.Networking.M2Mqtt.MqttClient.SendReceive (uPLibrary.Networking.M2Mqtt.Messages.MqttMsgBase msg, Int32 timeout) (at Assets/MQTT/scripts/MqttClient.cs:1115) uPLibrary.Networking.M2Mqtt.MqttClient.SendReceive (uPLibrary.Networking.M2Mqtt.Messages.MqttMsgBase msg) (at Assets/MQTT/scripts/MqttClient.cs:1101) uPLibrary.Networking.M2Mqtt.MqttClient.Connect (System.String clientId, System.String username, System.String password, Boolean willRetain, Byte willQosLevel, Boolean willFlag, System.String willTopic, System.String willMessage, Boolean cleanSession, UInt16 keepAlivePeriod) (at Assets/MQTT/scripts/MqttClient.cs:565) uPLibrary.Networking.M2Mqtt.MqttClient.Connect (System.String clientId) (at Assets/MQTT/scripts/MqttClient.cs:476) mqttTest.Start () (at Assets/MQTT/scripts/test/mqttTest.cs:22)

直接用代码 复制进来,运行出错。

我对C# u3d也不熟悉,没法解决这个问题,我只是简单的在u3D上跑通过

回到顶部