当前位置: 首页 > 后端技术 > PHP

PHPMQTTv1.3.1发布,MQTT协议解析&协程客户端

时间:2023-03-29 21:06:21 PHP

上一版本发布的知乎文章中有用户评论。我遇到了握手失败。联系我后,我测试了一下。我这里没问题,但是删了一段代码:$will=['topic'=>'','qos'=>0,'retain'=>0,'message'=>'',];$client->connect(true,$will);改为直接connect$client->connect();由于使用的是MQTT3,MQTT5中没有code属性,只能通过抓包获取错误原因。这里改成MQTT5后,可以直接获取错误原因,比如下面的代码,可以获取错误原因useSimps\MQTT\Client;useSimps\MQTT\Config\ClientConfig;useSimps\MQTT\Hex\ReasonCode;使用functionSwoole\Coroutine\run;run(function(){$config=newClientConfig();$config->setUserName('')->setPassword('')->setClientId(Client::genClientID())->setKeepAlive(10)->setProtocolLevel(5)->setDelay(3000)//3s->setMaxAttempts(5)->setSwooleConfig(['open_mqtt_protocol'=>true,'package_max_length'=>2*1024*1024,]);$client=newClient('broker.emqx.io',1883,$config);$will=['topic'=>'','qos'=>0,'retain'=>0,'message'=>'byebye',];$res=$client->connect(true,$will);var_dump($res,ReasonCode::getReasonPhrase($res['code']));});将code改成原因,可以得到错误原因:TopicNameinvalidarray(3){["type"]=>int(2)["session_present"]=>int(0)["code"]=>int(144)}string(18)"TopicNameinvalid"查看MQTT协议文档,你会发现:TheWillTopicMUSTbeaUTF-8EncodedStringasdefinedwillmessageThetopicincan'tbeempty,it必须是长度大于0的有效UTF-8字符串,所以这个版本增加了限制。如果有will消息,topic为空,会直接抛异常:PHPFatalerror:UncaughtSimps\MQTT\Exception\ProtocolException:Topiccannotbeempty更新日志增强添加isMQTT5方法(f27f85c)增加常量可见性(#41)getContents方法增加getArray参数,客户端回复对端ACK(#42)增加Message测试(8f7fe30)更新Message文档(a41654b)更新ProtocolException并增加测试(19a6bee)修正willmessage主题不能为空(b56fda1)关于PHPMQTTMQTT协议解析&协程客户端适用于PHP的MQTT协议解析和协议程序客户端支持MQTT协议3.1、3.1.1、5.0版本,支持QoS0、QoS1、QoS2。第一个PHP库文档支持MQTTv5.0协议:https://mqtt.simps.ioGitHub:https://github.com/simps/mqttGitee:https://gitee.com/phpiot/mqtt支持记得点个Star~